开发者

Problem with adding nodes to a treeview

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 locatio开发者_运维百科n 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!


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);


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.


in here:

TreeNode nd = treeView1.Nodes[0];

you are assigning the node node1 to the nd reference.

when you later add nd to the other TreeView you get the error because node1 is already bound to the other TreeView.

if you really need to do this, you should copy/close the node and not simply reference it as you are doing right now.


You are trying to add the same node into 2 different treeviews

TreeNode nd = treeView1.Nodes[0]; //make nd reference treeView1.Nodes[0]
treeView2.Nodes.Add(nd);//  add treeView1.Nodes[0] into treeView2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜