Tree error in winforms

I have three Buttons, one TextBoxand a TreeView. I add nodes dynamically to TreeView. I used some code and it works for the first (root) button. It shows an error Object reference not set to an instance of an objectfor the other two buttons. My three buttons: Add root, Add child, Delete.

My code is:

private void button1_Click(object sender, EventArgs e)
{
    TreeNode t;
    t = treeView1.Nodes.Add(textBox1.Text);
}

private void button2_Click(object sender, EventArgs e)
{
    TreeNode t;
    t = treeView1.SelectedNode;
    t.Nodes.Add(textBox1.Text);
    treeView1.SelectedNode.ForeColor = Color.Red;
}

private void button3_Click(object sender, EventArgs e)
{     
    treeView1.SelectedNode.Remove();
}
+3
source share
3 answers

An exception occurs when accessing treeView1.SelectedNodewhen at this moment there is no selected item.

The fix could be:

private void button3_Click(object sender, EventArgs e)
{
    if (treeView1.SelectedNode != null)
        treeView1.SelectedNode.Remove();
}
+1
source

Possible problem: you iddnt select a newly added / existing element in the treeview node before deleting / adding child nodes to it.

You check what t is before adding the child.

, root, , .

+1

It is possible, you have not selected anything, you can tell the user to choose, or you can choose manually.

private void button3_Click(object sender, EventArgs e)
{
    if (treeView1.SelectedNode != null)
        treeView1.SelectedNode.Remove();
   else
      Messagebox.Show ("Please select the node first");
}

private void button1_Click(object sender, EventArgs e)
    {
        TreeNode t;
        t = treeView1.Nodes.Add(textBox1.Text);
        treeView1.SelectedNode = t;

    }
0
source

All Articles