Checking if node exists and adding child node

c#, visual-studio-2010

Solution

In which part do you get the error? In the if or in the else?

Also, your code could be much simpler:

if(comboBox3.Text == "Books")
{
    if (!treeView1.Nodes.ContainsKey("Books"))
        treeView1.Nodes.Add("Books");

    treeView1.Nodes["Books"].Nodes.Add(textBox1.Text);
}

Edit:

When adding a TreeNode, you have to provide a name for the node. Only then can you get a node of the collection by accessing the collection through a name. If you don't set a name, you can still access the collection by using an index. But in this case you're using a string-key, therefore you also have to provide a name for the Books-TreeNode:

if(comboBox3.Text == "Books")
{
   if (!treeView1.Nodes.ContainsKey("Books"))
   {
       TreeNode booksNode = new TreeNode("Books");
       booksNode.Name = "Books";
       treeView1.Nodes.Add(booksNode);
   }

   treeView1.Nodes["Books"].Nodes.Add(textBox1.Text);
}

And again shorter (but perhaps less readable) this would be:

if(comboBox3.Text == "Books")
{
   if (!treeView1.Nodes.ContainsKey("Books"))
       treeView1.Nodes.Add(new TreeNode("Books") { Name = "Books" });

   treeView1.Nodes["Books"].Nodes.Add(textBox1.Text);
}

Problem

Since it's impossible to make nodes invisible, I decided to don't create them until I'll need them. My code: ``` if(comboBox3.Text == "Books") { if (treeView1.Nodes.ContainsKey("Books") == true) { treeView1.Nodes["Books"].Nodes.Add(textBox1.Text); } else if (treeView1.Nodes.ContainsKey("Books") == false) { treeView1.Nodes.Add("Books"); treeView1.Nodes["Books"].Nodes.Add(textBox1.Text); } } ``` In `ComboBox` there's few categories. It's code that is responsible for "Books". In TextBox I'm writing title and after clicking a button, this code is starting to work. First, it is checking if root node "Books" exists. If it is, it just add anything that is inside textbox as child node. But if not, it creates root node called "Books" and after that adds a child node. Im getting error in this line: ``` treeView1.Nodes["Books"].Nodes.Add(textBox1.Text); ``` Error: ``` NullReferenceException was unhandled ``` Also, is that possible to change index number, ie. I want to make 5 categories, but also I want to have specific order, let's say 1.House 2.Cars 3.Books 4.Phones 5.Bikes and I want to add first Books, then Cars, an then Bikes. Is there anything to change index number?

Original source