Search code examples
c#asp.netwebmethod

Showing data like a tree in code behind


I have a table as listed below

ID   Name   Parent
1     A       0
2     B       1
3     c       1
4     D       2
5     E       2
6     F       0
..    ..      ..

What I need is to show it like

 - A
    -B
     - D
     - E 
    -C

 - F

I am making datatables in c# like

I am getting the data with jquery-ajax and preparing the html from a web method, but I don't want to use any plugin for making the treeview.

Select The records in dtParent where Parent = 0

After this I am trying to filter the records for child entries.

I believe this can be easily done with the recursion but I am not able to find the correct logic.

The code I tried (dtGoals is table where I have all the records and in dtData I am getting only Parents)

dtData = dtGoals;
dtData.DefaultView.RowFilter = "ID = " + dtGoals.Rows[goalCount]["GoalId"].ToString();
dtData.AcceptChanges();
dtData = dtData.DefaultView.ToTable();

After RowFilter Parent records are in dtData. Make the tree node with first record (ID = 1). Now I don't know how to proceed.

Any help will be appreciated.

Thanks in advance.


Solution

  • public class Item
    {
        public Item()
        {
            Children = new List<Item>();
        }
    
        public int Id { get; set; } 
        public string Name { get; set; } 
        public int ParentId { get; set; }
        public List<Item> Children { get; set; } 
    }
    
    public class TreeBuilder
    {
        public TreeBuilder(IEnumerable<Item> items)
        {
            _items = new HashSet<Item>(items);
            TreeRootItems = new List<Item>();
            TreeRootItems.AddRange(_items.Where(x => x.ParentId == 0));
            BuildTree(TreeRootItems);
        }
    
        private readonly HashSet<Item> _items;
        public List<Item> TreeRootItems { get; private set; }
    
    
        public void BuildTree(List<Item> result)
        {
            foreach (var item in result)
            {
                item.Children.AddRange(_items.Where(x => x.ParentId == item.Id));
                BuildTree(item.Children);
            }
        }
    }