0

It has the value but don't know why still throwing nullRefrenceException.

This is my code for treeView with ChildView.

I want to make a treeView with parent and child from DataSet.

This is the result of my query

Code:

adp3 = new SqlDataAdapter("select country.CountryId  , country.CountryName ,` city.CityId , city.CityName "+
                          " from Country as country join City as city on city.CountryId = country.CountryId order by cityid ", Program.con);
adp3.Fill(ds,"bb");

this.mtree.Nodes.Clear();
string mdt = "";
string mref = "";
string mtitle = "";

foreach (DataRow row in ds.Tables["bb"].Rows)
{
    if (!row["Countryname"].ToString().Equals(mdt.Trim()))
    {
        TreeNode node = new TreeNode();
        node.Name = (string)row["CountryId"].ToString().Trim();
        node.Text = row["CountryName"].ToString();
        this.mtree.Nodes.Add(node);
        mdt = row["CountryName"].ToString().Trim();
        mtitle = "";
    }
    else if (!row["CityName"].ToString().Equals(mtitle.Trim()))
    {
        TreeNode node2 = new TreeNode();
        node2.Name = (string)row["CityId"].ToString().Trim();
        node2.Text = row["CityName"].ToString().Trim();
        this.mtree.Nodes[mdt.Trim()].Nodes.Add(node2);
        mtitle = row["CityName"].ToString().Trim();
    }
}
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Brendom
  • 123
  • 1
  • 10
  • 1
    Please add full error message to your question. – Taher Rahgooy Aug 27 '15 at 19:36
  • 1
    Knowing which line wouldn't hurt either. – Broots Waymb Aug 27 '15 at 19:37
  • Object reference not set to an instance of an object. on line this.mtree.Nodes[mdt.Trim()].Nodes.Add(node2); – Brendom Aug 27 '15 at 19:38
  • 1
    So which expression is null? `mtree`? `mtree.Nodes`? `mdt`? `mtree.Nodes[mdt.Trim()]`? `mtree.Nodes[mdt.Trim()].Nodes`? There's *way* too much going on in that single statement... introduce some more local variables and you'll have a much better time of it... – Jon Skeet Aug 27 '15 at 19:42
  • #jonSkeet this.mtree.Nodes[mdt.Trim()].Nodes.Add(node2); this expression is null – Brendom Aug 27 '15 at 19:47
  • And instead of writing a question, try to use the debugger. Usually these problems are really simple to discover with the debugger – Steve Aug 27 '15 at 19:47

1 Answers1

0

You haven't assigned anything to the mdt variable in the else if.

In the first branch, you have it assigned as

mdt = row["CountryName"].ToString().Trim();

B Wells
  • 48
  • 7