How to Reuse TreeNodeCollection in Windows Forms apps

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:

1
2
3
4
5
TreeNode[] nodes = new TreeNode[treeView1.Nodes.Count];
treeView1.Nodes.CopyTo(nodes,0);
selectForm.treeView1.Nodes.AddRange(nodes);

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)

1
2
3
4
5
6
7
8
9
10
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