Converting TreeNode to DataTable Dynamically

There are plenty of methods to convert datatable into treeview (treenode) like this. But is there any way to do create a datatable maintaining hierarchy. For ex. if TreeNode is like

A-A1
 -A2-A21
    -A22
B-B1
 -B2-B21
 -B3-B31
    -B32-B321
        -B322
    -B33
 -B4

should look like following in datatable. Then i can either save it in the databse or show it to the user in a datagrid.

All column can have take string values.

Is there any way so i can pass a treenode to a function & it will create datatble like this dynamically. treenode structure will change everytime that's why i can not hardcode it. Suppose i have a recursive function like this.

public void CreateData(TreeNode trn)
{

   foreach(TreeNode t in trn.Nodes)
   {
       CreateData(t);
   }

}

i am facing difficulty in understanding flow of code for recursive function. any suggestion is appreciated.

Thanks.

Answers


Here's a pseudo code, hope it will help you to deal with your problem

private void getNodeList()
{
    //This will hold your node text
    List<string> nodeTextList = new List<string>();
    //loop through all teeview nodes
    foreach(TreeNode rootNode in treeView.Nodes)
    {
       //Add root node to list
       nodeTextList.Add(rootNode.Text);
       //Do recursive getter to get child nodes of root node
       getChildNodes(rootNode, nodeTextList);

    }
    //Do with nodeTextList what ever you want, for example add to datatable.
}

private void getChildNodes(TreeNode rootNode, List<string> nodeTextList)
{
   foreach(TreeNode childNode in rootNode.Nodes)
   {
       //Add child node text
       nodeTextList.Add(childNode.Text);      
       getChildNodes(childNode, nodeTextList);
   }
}

Need Your Help

sql server, composite keys - ignoring duplicate

sql sql-server composite-key

Is there a way to prevent sql from throwing an error when I try to save a record that already exists. I've got a composite key table for a many-to-many relationship that has only the two values, wh...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.