Tanya
Tanya

Reputation: 1621

How to add nodes of one instance of treeview to the another instance of same treeview

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.

Upvotes: 3

Views: 1376

Answers (4)

Ray Akkanson
Ray Akkanson

Reputation: 1

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

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

Upvotes: 0

DeveloperX
DeveloperX

Reputation: 4683

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

Upvotes: 1

Mamta D
Mamta D

Reputation: 6460

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

Upvotes: 0

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234534

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.

Upvotes: 0

Related Questions