开发者

treeview error in winforms

开发者 https://www.devze.com 2023-03-11 05:38 出处:网络
I have three Buttons, one TextBox and a TreeView. I am adding nodes dynamical开发者_StackOverflow社区ly to the TreeView. I used some code and it is working for the first(root) button. It shows Object

I have three Buttons, one TextBox and a TreeView. I am adding nodes dynamical开发者_StackOverflow社区ly to the TreeView. I used some code and it is working for the first(root) button. It shows Object reference not set to an instance of an object error for other two buttons. My three buttons are: Add root, Add child, Delete.

My code:

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();
}


The exception is thrown when you access treeView1.SelectedNode when there is no selected item at that moment.

The fix could be:

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


The possible issue is, you iddnt select the newly added/existing item in treeview node before deleting/adding child nodes on that.

You check what is t before performing adding child.

First time its working because, root is selected, next time not working because the new item added is not selected anymore.


This is proably you didnt select anything, you can tell user to select or you can manually select.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号