PotatoBox
PotatoBox

Reputation: 608

Deleting child nodes in treeView

There's my code:

private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (treeView1.SelectedNode != null)
    {
         if (treeView1.SelectedNode.Parent == null) treeView1.SelectedNode.Remove();
         else if (treeView1.SelectedNode.Parent.Nodes.Count == 1) treeView1.SelectedNode.Parent.Remove();
         else treeView1.SelectedNode.Remove();
    }
     XDocument doc = XDocument.Load("test.xml");
     if (treeView1.SelectedNode.Parent != null)
     {
         var xElement = (from q in doc.Elements("dogs").Elements("dog")
                        where q.Attribute("id").Value == treeView1.SelectedNode.Tag.ToString()
                        select q);
            foreach (var a in xElement)
                a.Remove();
            doc.Save("test.xml");
}

I want to search through my file for id value and if program will find it, it compares it to tag of selected node, and if it finds it, it'll delete this node. And everytime I'm trying to delete any node, error NullReferenceException was unhandled appears.

Upvotes: 1

Views: 9995

Answers (1)

Aaron Viviano
Aaron Viviano

Reputation: 306

When you call:

treeView1.SelectedNode.Remove();

This will either set your treeView1.SelectedNode to null or set the SelectedNode to the removed node's parent or to the next available node.

Also this code will set the parent, of the node you removed, to null. These two cases are likely the root cause of your exception. I would suggest simply setting a temporary variable to point to the node you want removed:

TreeNode node = treeView1.SelectedNode;
treeView1.SelectedNode.Remove();

Then simply change your code to:

TreeNode node = treeView1.SelectedNode;
if (treeView1.SelectedNode != null)
{
    if (treeView1.SelectedNode.Parent == null) 
        treeView1.SelectedNode.Remove();
    else if (treeView1.SelectedNode.Parent.Nodes.Count == 1) 
        treeView1.SelectedNode.Parent.Remove();
    else 
        treeView1.SelectedNode.Remove();
}

XDocument doc = XDocument.Load("test.xml");

var xElement = (from q in doc.Elements("dogs").Elements("dog")
                where q.Attribute("id").Value == node.Tag.ToString()
                select q);
foreach (var a in xElement)
    a.Remove();
doc.Save("test.xml");

Upvotes: 3

Related Questions