19 February 2009
How to reuse TreeNodeCollection in Windows Forums 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];
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)
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;
}
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using
Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.