Mostafa Armandi
Mostafa Armandi

Reputation: 939

Duplicate TreeView's undelying rows to create a copy of exising TreeView

hi to the best my real friends . thank you and my favorite StackOverFlow.com

i have a TreeView control to view some hierarchical data . as you know there is a underlying DataTable (base on a sql server table) as DataSource to this TreeVeiw .

my problem is : how to duplicate one root and entire of it's leaves as a new branch of my TreeView .

duplicating a TreeView node is kind of simple i think (by using TreeNode Clone() method) . but what about underlying DataTable ? how to copy entire tree rows into the same table ? the ID column is identity but how to set ParentID column base on the recently inserted parent row in the table ?

Thanks in advance

Upvotes: 2

Views: 686

Answers (1)

Mike Christian
Mike Christian

Reputation: 1536

The most direct approach is to use a recursive method that iterates the cloned tree nodes. Each node will locate and update its own record in the DataTable object. Here's a basic WinForm code-behind:

using System;
using System.Data;
using System.Windows.Forms;

namespace Demo {
    public class TestClass {
        DataTable table;

        public void Initialize() {
            table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("ParentID", typeof(int));
            table.Columns.Add("Text", typeof(String));
        }

        private void UpdateTreeData(TreeNode parentNode) {
            int parentId = Convert.ToInt32(parentNode.Tag);
            int childId;
            foreach (TreeNode n in parentNode.Nodes)
            {   // Assuming Tag contains the table ID value...
                childId = Convert.ToInt32(n.Tag);
                table.Select("ID = " + childId.ToString())[0]["ParentID"] = parentId;
                UpdateTreeData(n);
            }
        }
    }
}
}

Upvotes: 1

Related Questions