0

It seems for removing a TreeNode i have to traverse to it's parent hence i did below just to find the original collection was modified even though it was a instance. Below is the code and tvRightTree is the TreeView of interest

TreeNodeCollection checkedNodeCollection = tvRightTree.CheckedNodes;
foreach (TreeNode checkedNode in checkedNodeCollection) {
  //if the to be removed node is parent then remove through treeview
  if (checkedNode.Parent != null) {
    //compiler does not allow modifying a collection that we iterate
    //hence resort to finding the parent and then remove
    TreeNode targetParent = tvRightTree.FindNode(checkedNode.Parent.ValuePath);
    targetParent.ChildNodes.Remove(checkedNode);
  } else
    tvRightTree.Nodes.Remove(checkedNode);
  }

What is the correct way to remove checked TreeNodes from the treeview?

dda
  • 6,030
  • 2
  • 25
  • 34
Deeptechtons
  • 10,945
  • 27
  • 96
  • 178

3 Answers3

3

You can avoid that error by using

for 

instead of foreach you use now, or use LINQ's ForEach, for example

for(int i=0;i<checkedNodeCollection.Count;i++)
{
    Treenode checkedNode = checkedNodeCollection[i]; 
    .... 
    ..  
}
Tigran
  • 61,654
  • 8
  • 86
  • 123
2

Here you should modify two functionalities

  1. Take a temperory TreeNodeCollection and add the filtered nodes to that collection and remove.
  2. Remove the code which will remove the nodes inside the loop. You can not remove an object from a collection, while looping in the same collection.
1

TreeNodeCollection is reference type so you did not copy the collection here:

TreeNodeCollection checkedNodeCollection = tvRightTree.CheckedNodes;

It is just link to tvRightTree.CheckedNodes
You need to copy items explicitly to new collection;

asktomsk
  • 2,289
  • 16
  • 23