Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with adding nodes to a treeview

Tags:

c#

winforms

When I was trying to copy node from one treeview to another, I got a strange error: "Cannot add or insert the item 'node1' in more than one place. You must first remove it from its current location or clone it. Parameter name: node" After searching for a while, I couldn't find any solution. I tried this in VB.NET and had the same error Code example:

TreeNode node1 = new TreeNode("node1");
node1.Name = "node1";
treeView1.Nodes.Add(node1);
TreeNode nd = treeView1.Nodes[0];
treeView2.Nodes.Add(nd);

Are there any solutions for this?


Thanks everyone! This works now!
like image 584
Nausik Avatar asked Jul 05 '11 11:07

Nausik


2 Answers

yes ,use deep copy

TreeNode nd = (TreeNode )treeView1.Nodes[0].Clone();

change your code to this

TreeNode node1 = new TreeNode("node1");
node1.Name = "node1";
treeView1.Nodes.Add(node1);
TreeNode nd = (TreeNode )treeView1.Nodes[0].Clone(); // clone the object
treeView2.Nodes.Add(nd);
like image 65
DeveloperX Avatar answered Oct 13 '22 00:10

DeveloperX


Have a look at TreeNode.Clone Method

Also from TreeNodeCollection.Add Method (TreeNode)

A TreeNode can be assigned to only one TreeView control at a time. To add the tree node to a new tree view control, you must remove it from the other tree view first or clone it.

like image 39
Adriaan Stander Avatar answered Oct 13 '22 00:10

Adriaan Stander