2012-12-22 124 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); 
    } 

} 

它拼命地工作对我来说,我希望这将有助于!