2

I have the following function to remove specific nodes from a tree view control

private void PruneTree(TreeNode tn)
{          
    foreach (TreeNode item in tn.Nodes)
    {                        
        PruneTree(item);            
    }
    if (tn.BackColor == Color.LightCoral && tn.Nodes.Count == 0)
    {
        tn.Remove();
    }
}

I call it on a treeview root node, but it throws NullReferenceExceptionfor the tn at tn.Nodes.

I don't expect a null item because I iterate the child nodes of a node and certainly they can't be null.

What could be the problem, I think as I remove some nodes from the tree, it affects the function.

Ahmad
  • 6,124
  • 6
  • 49
  • 90

1 Answers1

4

When you remove items, you break the enumeration.

To prevent this from happening, loop in reverse order like this:

for(int i = tn.Nodes.Count - 1 ; i >= 0 ; i--)
{
    TreeNode item = tn.Nodes[i];
   //....
}

This makes sure that you remove items with higher indexes first, so the enumeration will not break.

Yacoub Massad
  • 26,006
  • 2
  • 31
  • 56
  • Thank you, I modified my question and the solution is again your answer, even if I remove the items recursively outside of the loop. (however the loop indirectly execute remove. – Ahmad Dec 27 '15 at 18:49
  • @Ahmad, you are welcome. I am not sure that I understand the last part of your comment. – Yacoub Massad Dec 27 '15 at 19:10
  • sorry for my English, I mean we usually see such an error and solution when we directly remove an item in a loop, but my code do it indirectly. (it calls itself recursively and inside the function I remove the given item). But anyway the solution is the same. – Ahmad Dec 27 '15 at 19:17