2012-12-22 121 views
2

我在數據庫中創建一個帳戶表,這些列:填充樹視圖從數據表

ID 
Name 
ParentID 

這是如何記錄已存儲的例子:

ID Name ParentID 
1 BANK A 0 
2 0001 1 
3 0002 1 
4 BANK B 0 
5 0001 4 
6 0002 4 

但該公司名稱不是來自數據庫,它來自代碼。那麼我怎樣才能像這樣展開樹視圖呢?

Company Name 
-BANK A 
--0001 
--0002 
-BANK B 
--0001 
--0002 

如何在C#中執行此操作?我也嘗試從HERE,但我仍然不明白。

回答

3

我發現了一段代碼在花費2小時製作複雜的算法之後,這對我非常有用:

//In Page load 
//select where id is null to retrieve the parent nodes 
//in a datatable (called table here) 
foreach (DataRow row in table.Rows) 
{ 
    TreeNode node = new TreeNode(); 
    node.Text = row["title"].ToString(); 
    node.Value = row["id"].ToString(); 
    //you can affect the node.NavigateUrl 

    node.PopulateOnDemand = true; 
    TreeView1.Nodes.Add(node); 
} 

然後創建TreeNodePopulate事件:

protected void TreeView1_TreeNodePopulate(Object sender, TreeNodeEventArgs e) 
{ 
    string id= e.Node.Value; 
    //do your "select from yourTable where parentId =" + id; 

    foreach (DataRow row in table.Rows) 
    { 
     TreeNode node = new TreeNode(row["title"], row["id"]) 
     node.PopulateOnDemand = true;  
     e.Node.ChildNodes.Add(node); 
    } 

} 

它拼命地工作對我來說,我希望這將有助於!