3

How to populate the nodes into the newtreeview1 which is the instance of the another treeview1 ? The nodes which is added to the "newtreeview1" should be available in the first instance of the treeview1?

for example; if the treeview1 contains

   |-- Node1
        |-- Node2
           | -- Node3
        |-- Node4

the newtreeview1 should also have the above nodes.

4 Answers 4

1

you can do this by cloning each node like this

    private void CopyNodes(TreeView srcTree, TreeView dstTree)
    {
        var ar = System.Array.CreateInstance(typeof(TreeNode), srcTree.Nodes.Count);
        treeView1.Nodes.CopyTo(ar, 0);
        foreach (TreeNode item in ar)
        {
            dstTree.Nodes.Add((TreeNode)item.Clone());
        }
    }

and call the function

CopyNodes(treeView1, treeView2);
Sign up to request clarification or add additional context in comments.

Comments

0

You need to copy the nodes. Something like:

otherTreeView.Nodes.Add(node.Text);

Depending on what you want, you need to pick an overload of the Add method that includes all the data you want to copy (key, text, and/or images). Just don't add the nodes directly, but instead their constituent parts.

2 Comments

ya. i tried that but it throws "The specified node cannot be added to a nodes collection that belongs to a different control." Exception
This exception is only thrown if you are adding the node directly. Re-read Martinho's answer.
0

You could try the approach given in this below link and serialize your tree contents. Then construct a new treeview based on the serialized contents. A big of a long-winded approach I know but this is guaranteed to add all the hierarchial data properly into the second treeview.

Save nodes from a treeview

Comments

0

You can just copy the TreeView1 instance and add additional nodes. Same thing as shown below

TreeView2 = TreeView1;
TreeView2.Nodes.Add(new TreeNode());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.