I have three Buttons, one TextBox and a TreeView. I am adding nodes dynamically 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.SelectedNodewhen there is no selected item at that moment.The fix could be: