Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c# - Recursive TreeView in ASP.NET

I have an object of type list from which I wish to use to populate a treeview in asp.net c#.

Each object item has:

id | Name | ParentId

so for example:

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.

I have had many problems trying to dynamically populate the treeview recursively in c# ASP.NET

Does any one have a simple solution?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...