Click here to Skip to main content
15,899,475 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to solve the Exception: Collection was modified; enumeration operation may not execute

Here the iterations are working fine but meanwhile i want to delete those child nodes.. may i knw how can i ?

C#
private void PrintRecursive(TreeNode treeNode, TreeView treeviewtemp2)
   {

      // (level-2 TreeNodes)
       int x = 0;
       foreach (TreeNode n in treeNode.ChildNodes)
       {
          

           var nodeName = n.Text;
           var nodeValue = n.Value;

           treeviewtemp2.Nodes[0].ChildNodes[x].ChildNodes.Remove(n);
           x++;

       }

   }


Thanks in advance
Posted
Updated 8-Aug-18 8:29am

Don't modify the collection during traversing it using "foreach". Actually, this is not really needed. For example, you can create a list of element references to be removed, and remove them all in a separate loop. By the way, such limitation is not applied to "for" loop, but you have to be extra careful. For example, one usual technique is to traverse the collection in reverse, if you are going to remove some elements. (Do I even have to explain why? This is really simple logic.)

Your code really have problems, so this fool-prof .NET feature really helps you. First of all, when you take some index ([0], [x], n) you have to make sure the element at this index really exists.

I'll leave re-writing your code for your home exercises. It's really important to learn how to solve such little problems all by yourself.

(Another hint: if you want to use "for", calculate count and store it in some local variable before the loop. Again, I hope I don't have to explain why.)

—SA
 
Share this answer
 
v2
Comments
CPallini 19-Aug-15 3:27am    
5.
Sergey Alexandrovich Kryukov 19-Aug-15 9:00am    
Thank you, Carlo.
—SA
I fix the problematic code with some changes. This problem often occurs in control collections. I was puzzled by it when trying to remove nodes from a TreeView control.



List<TreeNode> treeList = new List<TreeNode>();
        foreach (TreeNode treeNode in treeViewFolderMove.Nodes)
        {
            treeList.Add(treeNode);
        }
        foreach (TreeNode treeNode in treeList)
        {
            if (treeNode.Value == Value)
            {
                this.treeViewFolderMove.Nodes.Remove(treeNode);
            }
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900