PotatoBox
PotatoBox

Reputation: 608

Delete empty root node in treeView

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

Afternoon

Night

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".

Upvotes: 0

Views: 3047

Answers (2)

King King
King King

Reputation: 63327

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

Upvotes: 1

John Kraft
John Kraft

Reputation: 6840

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

Upvotes: 1

Related Questions