views:

3687

answers:

4

Hi,

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...

+2  A: 

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

 }
Bob
+5  A: 

Not quite.

Trees are usually handled best by not loading everything you can at once. So you need to get the root node (or topic) which has no parentIDs. Then add them to the trees root node and then for each node you add you need to get its children.

foreach (DataRow row in topicsWithOutParents.Rows)
{
   TreeNode node = New TreeNode(... whatever);
   DataSet childNodes = GetRowsWhereParentIDEquals(row["topicId"]);
   foreach (DataRow child in childNodes.Rows)
   { 
       Treenode childNode = new TreeNode(..Whatever);
       node.Nodes.add(childNode);
   }
   Tree.Nodes.Add(node);
}
Brody
+1  A: 

the "..Whatever" should pass the childnodes of that particular childnode. This would make a recursive algorithm if the foreach loop was done for each TreeNode constructor.

Wouter
+1  A: 

When there are no Large Amounts of Data then it is not good to connect database, fetch data and add to treeview node again and again for child/sub nodes. It can be done in single attempt. See following sample:
http://urenjoy.blogspot.com/2009/08/display-hierarchical-data-with-treeview.html

Brij