动态地将TreeNode转换为DataTable

时间:2011-11-30 07:25:30

标签: c# winforms datatable treenode

有很多方法可以将数据表转换为treeview(treenode),例如this。但有没有办法创建一个数据表维护层次结构。对于前者如果TreeNode就像

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

应该在datatable中看起来如下。然后我可以将其保存在数据库中,或者通过datagrid将其显示给用户。

enter image description here

所有列都可以包含string个值。

有什么方法可以将treenode传递给功能&它将动态创建这样的数据。 treenode结构每次都会改变,这就是我无法对其进行硬编码的原因。假设我有这样的递归函数。

public void CreateData(TreeNode trn)
{

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

}

我在理解递归函数的代码流方面遇到了困难。 任何建议都表示赞赏。

感谢。

2 个答案:

答案 0 :(得分:1)

这是一个伪代码,希望它能帮助您解决问题

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);
   }
}

答案 1 :(得分:0)

如果您无法理解该功能或其功能,您可能需要阅读Depth-first search。这正是你正在做的事情+你应该添加保存你现在所在节点的代码。