Expand all parent nodes of a specific node in C# treeview

3.4k views Asked by At

I'm creating a recursive find method in C# Treeview, and I want to expand all parent nodes of the fined node. This is my code:

private void RecursivFindNode(RadTreeNodeCollection nodes, string nodeName2Find)
{
   foreach (RadTreeNode node in nodes)
   {
      if (node.Text.Contains(nodeName2Find))
       {
           node.BackColor = Color.Yellow;
           NodeExpand(node);
       }
       RecursivFindNode(node.Nodes);
    }

}

private void NodeExpand(RadTreeNode nodeExpand)
{
   while (nodeExpand != null)
   {
       nodeExpand.Expand();
       nodeExpand = nodeExpand.Parent;
    }
}

But I'm getting this error:

Collection was modified; enumeration operation may not execute.

I know I can't modify the item which is in a foreach loop. So how can I make it work?

1

There are 1 answers

0
Ghasem On BEST ANSWER

So as @Vlad suggested, I changed my foreach to this:

foreach (var node in nodes.OfType<RadTreeNode>().ToArray())

And now everything works fine. :)