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:

TreeNode[] nodes = new TreeNode[treeView1.Nodes.Count];



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)

        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;