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?
So as @Vlad suggested, I changed my
foreach
to this:And now everything works fine. :)