在ASP.NET TreeView控件递归 [英] Recursive TreeView in ASP.NET
问题描述
我有类型列表中的对象从中我希望用来填充asp.net C#中的树视图。
I have an object of type list from which I wish to use to populate a treeview in asp.net c#.
每个对象的项目有:
id | Name | ParentId
因此,例如:
so for example:
id | Name | ParentId
-------------------------
1 | Alice | 0
2 | Bob | 1
3 | Charlie | 1
4 | David | 2
在上面的例子中,亲本会具有两个孩子鲍勃和Charlie爱丽丝。大卫是Bob的孩子。
In the above example, the parent would be Alice having two children Bob and Charlie. David is the child of Bob.
我有很多问题想递归动态填充树视图在C#ASP.NET
I have had many problems trying to dynamically populate the treeview recursively in c# ASP.NET
没有任何一个有一个简单的解决方案?
Does any one have a simple solution?
顺便说一句:你可以使用People.Id,People.Name和People.ParentId访问成员,因为它是属于列出对象
Btw: you can use People.Id, People.Name and People.ParentId to access the members since it is an object belonging to list.
我至今(许多尝试做),但不知道它会多么有用张贴你我的code。
I can post you my code so far (many attempts made) but not sure how useful it will be.
推荐答案
我想这应该让你开始。我创建了一个为MyObject
类模仿你的对象。
I think this should get you started. I created a MyObject
class to mimic your object .
public class MyObject
{
public int Id;
public int ParentId;
public string Name;
}
下面是recursivley添加基于列表中的树视图节点的方法。
Here is a method to recursivley add tree view nodes based on the list.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<MyObject> list = new List<MyObject>();
list.Add(new MyObject(){Id=1, Name="Alice", ParentId=0});
list.Add(new MyObject(){Id=2, Name="Bob", ParentId=1});
list.Add(new MyObject(){Id=3, Name="Charlie", ParentId=1});
list.Add(new MyObject(){Id=4, Name="David", ParentId=2});
BindTree(list, null);
}
}
private void BindTree(IEnumerable<MyObject> list, TreeNode parentNode)
{
var nodes = list.Where(x => parentNode == null ? x.ParentId == 0 : x.ParentId == int.Parse(parentNode.Value));
foreach (var node in nodes)
{
TreeNode newNode = new TreeNode(node.Name, node.Id.ToString());
if (parentNode == null)
{
treeView1.Nodes.Add(newNode);
}
else
{
parentNode.ChildNodes.Add(newNode);
}
BindTree(list, newNode);
}
}
这篇关于在ASP.NET TreeView控件递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!