How to Reuse TreeNodeCollection in Windows Forms apps
1 min read
I’m creating an app and need the same data set for two tree views. Nodes.AddRange only works with a TreeNode[] and the TreeNodeCollection is read-only and doesn’t have a ctor.
I first tried something like this:
TreeNode[] nodes = new TreeNode[treeView1.Nodes.Count];
treeView1.Nodes.CopyTo(nodes,0);
selectForm.treeView1.Nodes.AddRange(nodes);
```python
But got this exception.
> \_Cannot add or insert the item ‘’ in more than one place. You must first remove it from its current location or clone it.> Parameter name: node\_
Apparently we need to first clone the nodes because they are already bound to the first TreeView.
Here’s the quick and dirty (feel free to make it cleaner w/ extension method, etc)
```csharp
selectForm.treeView1.Nodes.AddRange(TreeViewUtility.CloneNodes(treeView1)); public static TreeNode[] CloneNodes(TreeView tree) { TreeNode[] nodes = new TreeNode[tree.Nodes.Count]; for(int i = 0; i < tree.Nodes.Count; i++) { nodes[i] = tree.Nodes[i].Clone() as TreeNode; } return nodes; }Share: