Populate TreeView from DataBase

Tarik picture Tarik · Dec 12, 2008 · Viewed 84.8k times · Source

I have a database table (named Topics) which includes these fields :

  1. topicId
  2. name
  3. parentId

and by using them I wanna populate a TreeView in c#. How can I do that ?

Thanks in advance...

Answer

Bob picture Bob · Dec 12, 2008

It will probably be something like this. Give some more detail as to what exactly you want to do if you need more.

//In Page load
foreach (DataRow row in topics.Rows)
{
    TreeNode node = new TreeNode(dr["name"], dr["topicId"])
    node.PopulateOnDemand = true;

     TreeView1.Nodes.Add(node);
 }
 ///
 protected void PopulateNode(Object sender, TreeNodeEventArgs e)
 {
     string topicId = e.Node.Value;
     //select from topic where parentId = topicId.
     foreach (DataRow row in topics.Rows)
     {
         TreeNode node = new TreeNode(dr["name"], dr["topicId"])
         node.PopulateOnDemand = true;

         e.Node.ChildNodes.Add(node);
     }

 }