Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy all treeView parent and children to another treeView c# WinForms

I am trying to copy the entire tree (exactly all nodes) of a treeview (completely) to another treeview using this code:

        TreeNodeCollection myTreeNodeCollection = treeView1.Nodes;

        TreeNode[] myTreeNodeArray = new TreeNode[treeView1.Nodes.Count];

        treeView1.Nodes.CopyTo(myTreeNodeArray, 0);

        treeView2.Nodes.AddRange(myTreeNodeArray);

But this does not allow me to do so, it asks to either delete the nodes in source treeview or use it Clone! How can I do that? I dont want my source treeview to lose anything in this process.

** UPDATE ** Ok guys I found a complicated code (for me!!) but how can I use this?

    public static T DeepTreeCopy<T>(T obj)
    {
        object result = null;
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            result = (T)formatter.Deserialize(ms); ms.Close();
        }
        return (T)result;
    } 
like image 717
Saeid Yazdani Avatar asked Apr 11 '11 10:04

Saeid Yazdani


2 Answers

Like MohD's answer, but with recursion to get all nodes. (Nodes of childnodes)

    public void CopyTreeNodes(TreeView treeview1, TreeView treeview2)
    {
        TreeNode newTn;
        foreach (TreeNode tn in treeview1.Nodes)
        {
            newTn = new TreeNode(tn.Text, tn.ImageIndex, tn.SelectedImageIndex);
            CopyChildren(newTn, tn);
            treeview2.Nodes.Add(newTn);
        }
    }
    public void CopyChildren(TreeNode parent, TreeNode original)
    {
        TreeNode newTn;
        foreach (TreeNode tn in original.Nodes)
        {
            newTn = new TreeNode(tn.Text, tn.ImageIndex, tn.SelectedImageIndex);
            parent.Nodes.Add(newTn);
            CopyChildren(newTn, tn);
        }
    } 
like image 88
kilad Avatar answered Sep 23 '22 18:09

kilad


Using the node.Clone() function works as well...

foreach (TreeNode node in treeViewSource.Nodes)
{
    treeViewTarget.Nodes.Add((TreeNode)node.Clone());
}

Adding a root node will help ensure the "PlusMinus" functionality is viewable.

TreeNode rootNode = new TreeNode("Root Node");
treeViewTarget.Nodes.Add(rootNode);
foreach (TreeNode node in treeViewSource.Nodes)
{
    rootNode.Nodes.Add((TreeNode)node.Clone());
}
rootNode.Expand();
like image 35
Jeff Johnson Avatar answered Sep 24 '22 18:09

Jeff Johnson