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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s