Why can't I assign TreeNode[] to two Treeview

2019-09-15 04:52发布

问题:

I get that this is not working, but could anybody explain to me WHY I can't do this? What's the mechanism that prevents me from doing thing in question?

So

TreeNode[] itemNodes = new TreeNode[2];
itemNodes[0] = new TreeNode("item1");
itemNodes[1] = new TreeNode("item2");

TreeNode[] botNodesFirst = new TreeNode[2];
botNodesFirst[0] = new TreeNode("bot1");
botNodesFirst[1] = new TreeNode("bot2");

TreeNode[] botNodesSecond = new TreeNode[3];
botNodesSecond[0] = new TreeNode("bot1");
botNodesSecond[1] = new TreeNode("bot2", itemNodes);
botNodesSecond[2] = new TreeNode("bot3");

TreeNode[] topNodes = new TreeNode[2];
topNodes[0] = new TreeNode("top", botNodesFirst);
topNodes[1] = new TreeNode("top2", botNodesSecond);

And then this works

foreach(TreeNode node in topNodes)
{
    trvTest.Nodes.Add(node);
}

But this does not

foreach(TreeNode node in topNodes)
{
    trvTest.Nodes.Add(node);
    trvTestSecond.Nodes.Add(node); 
}

Thanks.

回答1:

The same TreeNode cannot be assigned to two TreeView simultaneously, remember that you are assigning reference to an object. In your case node can't define which control is its parent.

But there is one strange thing and one not obvious. Not obvious is that assigning node to new TreeView is prohibited while it could be rewritten and just disappear from first Tree and appear in second. But this is by design and we have to live with that, that is not so bad.

Strange thing is that my sample project has run correctly and displayed top and top2 nodes in first tree and item1 and item2 in second tree. It seems that those assignments to trees are not resolved while creating view because when I debugged that and took a look inside TreeNodeCollection, continuation of debugging threw an exception that nodes cannot be assigned to more than one tree and you have to clone them or remove from first tree. This is kind of bug or race.



标签: c# treeview