2011-11-30 170 views
0

有很多方法可以将数据表转换为treeview(treenode),如this。但是有什么办法可以创建一个可数据维护的层次结构。例如。如果TreeNode就像动态地将TreeNode转换为DataTable

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

应该看起来像在数据表中。然后,我可以将其保存在数据库中,或者以datagrid的形式显示给用户。

enter image description here

所有列可以有取string值。

有没有什么办法,我可以通过treenode函数&它会动态地创建这样的数据。 treenode结构每次都会改变,这就是为什么我不能对它进行硬编码。假设我有这样的递归函数。

public void CreateData(TreeNode trn) 
{ 

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

} 

我很难理解递归函数的代码流。 任何建议表示赞赏。

谢谢。

+1

你的意思是保存到数据表或数据库?无论如何,这个数据表有什么结构。根据你的例子,这个数据表有一列(类型字符串),或者这个表有多个(动态创建)列(类型字符串)。请添加更多信息! –

+0

阅读此:http://stackoverflow.com/questions/192220/what-is-the-most-efficient-elegant-way-to-parse-a-flat-table-into-a-tree/192462#192462 –

+0

Hippo通常在这些情况下,您有一个可以说ID,标题和ParentID的表,每个非根节点都有parentID指向表中的父节点记录。我认为你应该这样做,而不是像你在问题中定义的表格那样。当你将它们绑定到像我提到的那样的表结构时,也可以认为有树形控件能够以这种方式完全填充。 –

回答

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

感谢伪代码,但是'NodeTextList'只是获取节点中存在的所有节点的名称。我无法维护孩子的父母关系。 –

+0

创建要举办小孩和家长的课程,制作该课程的列表并填写它 – Reniuz

0

如果您无法理解该功能或应该如何工作,那么您可能需要阅读Depth-first search。它完全不需要你在做什么+你应该添加代码来保存你所在的节点。