2011-11-30 175 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。它完全不需要你在做什麼+你應該添加代碼來保存你所在的節點。