从 DataTable 填充 TreeView [英] Populate TreeView from DataTable
问题描述
我在我的数据库中创建了一个帐户表,其中包含以下列:
I have created an account table in my database, with these columns:
ID
Name
ParentID
这是记录如何存储的示例:
This is an example of how records have been stored:
ID Name ParentID
1 BANK A 0
2 0001 1
3 0002 1
4 BANK B 0
5 0001 4
6 0002 4
但是公司名称不是来自数据库,而是来自代码.那么我怎样才能像这样扩展 TreeView
呢?
But the company name does not come from database, it comes from code. So how can I expand the TreeView
like this?
├─ BANK A
│ ├─ 0001
│ └─ 0002
└─ BANK B
├─ 0001
└─ 0002
我怎样才能在 C# 中做到这一点?我也从 HERE 尝试过,但我还是不明白.
How can I do this in C#? I also tried from HERE but I still don't understand it.
推荐答案
在花了 2 小时制作复杂的算法后,我找到了一段非常适合我的代码:
i have found a piece of code that worked great for me after spending 2h to make complicated algorithlms :
//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 事件:
then create the TreeNodePopulate event :
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);
}
}
它对我来说太棒了,我希望它会有所帮助!
it worked like hell for me, i hope it will help !
这篇关于从 DataTable 填充 TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!