Copy one tree view to another – Recursive Method

Below is the practical example of recursive method to copy one tree view control’s nodes into another tree view.

aspx file code:
TreeView

CSharp file code:

private void IterateTreeNodes(TreeNode originalNode, TreeNode rootNode)
    {
        foreach(TreeNode childNode in originalNode.ChildNodes)
        {
            TreeNode newNode = new TreeNode(childNode.Text);
            newNode.Text = childNode.Text;
            rootNode.ChildNodes.Add(newNode);
            IterateTreeNodes(childNode, newNode);
        }
    }
    protected void btnCopyTreeView_Click(object sender, EventArgs e)
    {
        foreach (TreeNode originalNode in TreeView1.Nodes)
        {
            TreeNode newNode = new TreeNode(originalNode.Text);
            newNode.Text = originalNode.Text;
            TreeView2.Nodes.Add(newNode);
            IterateTreeNodes(originalNode, newNode);
        }
    }
Advertisements

#tree-view-control