ASP.NET 中的递归树视图 [英] 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
例如:
id | Name | ParentId
-------------------------
1 | Alice | 0
2 | Bob | 1
3 | Charlie | 1
4 | David | 2
在上面的例子中,父母是爱丽丝,有两个孩子鲍勃和查理.大卫是鲍勃的孩子.
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.
到目前为止,我可以向您发布我的代码(进行了多次尝试),但不确定它会有多大用处.
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;
}
这里是一种基于列表递归添加树视图节点的方法.
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 中的递归树视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!