Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a TreeView recursively

Well, I have a table in a database called departments and it has the following fields: Id, Parent, Name, IsActive.

What is the best way to fill a TreeView with this data?

like image 370
user3354807 Avatar asked Feb 26 '14 08:02

user3354807


1 Answers

you can use the following

1- retrieve the data from the database into datatable or list call it as dataList

public void PopulateTree(ref TreeNode root,List<Department> departments)
{
    if(root==null)
    {
          root=new TreeNode();
          root.Text="Departments";
          root.Tag=null;
          // get all departments in the list with parent is null
          var details=departments.Where(t=>t.Parent==null);
          foreach(var detail in details)
          {
              var child= new TreeNode(){
                  Text=detail.Name,
                  Tage=detail.Id,
              };
              PopulateTree(ref child,departments);
              root.Nodes.Add(child);
          }      
    }
    else
    {
         var id=(int)root.Tag;
         var details=departments.Where(t=>t.Parent==id);
         foreach(var detail in details)
         {
              var child= new TreeNode(){
                  Text=detail.Name,
                  Tage=detail.Id,
              };
              PopulateTree(ref child,departments);
              root.Nodes.Add(child);
         }
    }
}

and in the Load event

TreeNode root=null;
var departments=query from database
PopulateTree(ref root,departments);

hope that this will help you

regards

like image 195
Monah Avatar answered Oct 31 '22 19:10

Monah