user3354807 user3354807 - 1 month ago 11
C# Question

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?

Answer

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