0
votes

Let's say I've got tree with 3 categories, each with 3 child nodes. I want to delete root node, when all child nodes gets deleted. I tried something like this:

        TreeNode current = treeView1.SelectedNode;
        TreeNode parent  = treeView1.SelectedNode.Parent;

        if (parent.Nodes.Count == 0)
        {
            parent.Nodes.Remove(current);
        }

And I placed it in Form1_Load. Unfortunatelly, when all child nodes are gone nothing happens. Is this code correct? Or maybe I misplaced it and I should place it somewhere else?

edit: My tree looks like this:

Morning

  • brush teeth
  • drink coffee

Afternoon

  • dinner
  • TV

Night

  • Sleep

So if I decide to delete "Sleep", I want also delete "Night". But If I decide to delete "TV", I want to keep "Dinner" and "Afternoon".

2
You're going from the child to the parent. Assuming there is no NullReferenceException thrown, parent.Nodes.Count will always be at least 1.Simon Belanger

2 Answers

1
votes

Try this:

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

If the parent is null, then you know that you are on a root node. So that node needs to be removed from the TreeView's Nodes collection directly. Otherwise, you can just remove the selected node from the parent. There's no reason to even look at the Node count.

Now, you also need to check that the current node is not null either; because it's perfectly reasonable to have no node in a tree selected.

TreeNode current = treeView1.SelectedNode;
if(current == null)
    return;

TreeNode parent  = treeView1.SelectedNode.Parent;
if (parent == null)
{
    treeView1.Nodes.Remove(current);
}
else
{
    parent.Nodes.Remove(current);
}