Solved

C# - Populating a TreeView from a DataSet

Posted on 2007-04-03
11
8,227 Views
Last Modified: 2009-12-15
Hi guys 'n gals,

I need some help in populating a treeView object from a Dataset, here is the structure of my Datatable:

UID, Name, ParentUID, DisplayOrder

UID is the Unique ID for that record
Name is the value I want to display in the TreeView
ParentUID is the UID of the Parent Node
DisplayOrder is the order in which everything will be displayed


If you need more information off of me to be able to solve this issue, please feel free to ask me!!

Cheers!
0
Comment
Question by:Cyber-Drugs
  • 6
  • 3
  • 2
11 Comments
 
LVL 13

Expert Comment

by:dungla
ID: 18848079
1. Query from database with DisplayOrder
SELECT UID, ParentUID, Name, DisplayOrder
FROM yourTable
ORDER BY ParentUID, DisplayOrder

2. Add Parent(s) node

3. Loop thru the parent(s) node, get the parent id then getting the children:
foreach (TreeNode parentNode in treeView.Nodes)
{
// parent id
int intParentUID = Convert.ToInt32(parentNode.Tag); // just for example I store the parent id to Tag of Node)
// now retrieve children from table
DataRow[] drowChildren = childTable.Select("ParentUID = " + intParentUID);
// add child node
foreach (DataRow drowChild in drowChildren)
{
TreeNode childNode = new TreeNode();
childNode.Text = drowChild["Name"].ToString();
childNode.Tag = Convert.ToInt32(drowChild["UID"]);
// add to parent node
parentNode.Nodes.Add(childNode);
}
}
0
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 18848886
Hi dungla,

Unfortunately that won't do the job, as there is an unlimited depth to this structure, rather than one child deep. I have the code I want in PHP, would posting it help all?


Cheers!
0
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 18848902
In case it helps, here is the PHP version of the code:



function catlist()
{
      $db = new DBClass;
      $db->DB();
      $db->Connect();
      $cat = array();
      $totalcats = '1';
      $maxid = '1';
      
      $cat_query = mysql_query("SELECT * FROM tblNavigator ORDER BY displayorder, cat_name ASC");
      
      while ($cattemp = mysql_fetch_array($cat_query))
      {
            $id = $cattemp['UID'];
            if ($maxid < $id) $maxid = $id;
            
            $cat[$totalcats]['id'] = $totalcats;
            $cat[$totalcats]['cat_id'] = $cattemp['UID'];
            $cat[$totalcats]['parent_id'] = $cattemp['ParentUID'];
            $cat[$totalcats]['name'] = $cattemp['cat_name'];
            
            $totalcats++;
      }
      
      if ($totalcats == '1')
      {
            $cat_list_bit = $vbphrase['music_nocat'];
      }
      else
      {
            for ($cid = '1'; $cid <= $maxid; $cid++)
            {
                  if ($cat[$cid]['parent_id'] == '0')
                  {
                        $cat_id = $cat[$cid]['cat_id'];
                        $cat_name = $cat[$cid]['name'];
                        $par_num = '0';
                        $cat_list_sub = subcat($cat_id, $cat, $maxid);
                        
                        $cat_list_bit .= "<img src=\"images/minus.gif\" border='0' style=\"cursor:hand;\" onClick=\"hide_sub_cat(c".$cat_id.", this)\">&nbsp;<a style=\"cursor:hand\" onclick=\"nav_click(".$cat_id.", '".$cat_name."')\"><img src=\"images/text_rich_colored.png\" alt=\"\" width=\"16\" height=\"16\" border=\"0\" />&nbsp;<strong>".$cat_name."</strong></a><br>
                        <span id=\"c$cat_id\" style=\"display:'none'\"><div style=\"margin-left: 15px\">".$cat_list_sub."</div></span>";
                  }
            }
      }
      
      $cat_list = $cat_list_bit;
      
      $db->Disconnect();
      return $cat_list;
}

function subcat($parent_id, $cat, $maxid)
{
      global $vbulletin, $vbphrase;
      
      for ($sub_id = 0; $sub_id <= $maxid; $sub_id++)
      {
            if ($cat[$sub_id]['parent_id'] == $parent_id)
            {
                  $cat_id = $cat[$sub_id]['cat_id'];
                  $cat_name = $cat[$sub_id]['name'];
                  
                  for ($n = '1';$n <= $par_num;$n++) $sub_cats_.='|-';
                  
                  $sub_cats_sub = subcat($cat_id, $cat, $maxid);
                  
                  $child_count = mysql_num_rows(mysql_query("SELECT * FROM tblNavigator WHERE ParentUID='".$cat_id."'"));
                  if ($child_count == 0)
                  {
                        $sub_cats .= $sub_cats_." <img src=\"images/leaf.gif\" border='0' style=\"cursor:hand\" onClick=\"hide_sub_cat(c".$cat_id.", this)\">&nbsp;<a style=\"cursor:hand\" onclick=\"nav_click(".$cat_id.", '".$cat_name."')\"><img src=\"images/text_rich_colored.png\" alt=\"\" width=\"16\" height=\"16\" border=\"0\" />&nbsp;".$cat_name."<a/><br>
                        <span id=\"c".$cat_id."\" style=\"display:'none'\"><div style=\"margin-left: 15px\">".$sub_cats_sub."</div></span>";
                  }
                  else
                  {
                        $sub_cats .= $sub_cats_." <img src=\"images/minus.gif\" border='0' style=\"cursor:hand\" onClick=\"hide_sub_cat(c".$cat_id.", this)\">&nbsp;<a style=\"cursor:hand\" onclick=\"nav_click(".$cat_id.", '".$cat_name."')\"><img src=\"images/text_rich_colored.png\" alt=\"\" width=\"16\" height=\"16\" border=\"0\" />&nbsp;".$cat_name."</a><br>
                        <span id=\"c".$cat_id."\" style=\"display:'none'\"><div style=\"margin-left: 15px\">".$sub_cats_sub."</div></span>";
                  }
            }
      }
      return $sub_cats;
}
0
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 18852222
Hey,

I decided to quick try your code to see if maybe it did the same thing as the large PHP function I have. When running it, I got the error:

Error      1      The name 'childTable' does not exist in the current context      C:\Documents and Settings\Justin Nel\My Documents\Visual Studio 2005\Projects\CartoLogix\CartoLogix\Form1.cs      55      42      CartoLogix


What should "childTable" be?
0
 
LVL 13

Expert Comment

by:dungla
ID: 18854999
childTable is the result of query

"SELECT UID, ParentUID, Name, DisplayOrder
FROM yourTable
ORDER BY ParentUID, DisplayOrder"

If you want to add more child, just make a recursive call to the method.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 18858422
Ok,

Currently it has no errors, but it displays this:

Top Level
- Top Level


Rather than:

Top Level
- Site 1
- etc...


I have added "Top Level" in manually as well as with the code, and it does as displayed above, but when I remove it, nothing is displayed at all. What changes do I need to make?

Cheers!


Code thus far:


        private void PopulateTreeView1()
        {
            MySqlConnection conn = new MySqlConnection(connString);
            DataSet ds = new DataSet();
            conn.Open();
            MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM tblNavigator ORDER BY ParentUID, displayorder", conn);
            adapter.Fill(ds);
            conn.Close();

            TreeNode treeTopLevel;

            DataTable childTable = new DataTable();
            childTable = ds.Tables[0];

            treeTopLevel = treeView1.Nodes.Add("Top Level");

            foreach (TreeNode parentNode in treeView1.Nodes)
            {
                int intParentUID = Convert.ToInt32(parentNode.Tag);
                DataRow[] dRowChildren = childTable.Select("ParentUID = " + intParentUID);
                foreach (DataRow dRowChild in dRowChildren)
                {
                    TreeNode childNode = new TreeNode();
                    childNode.Text = dRowChild["cat_name"].ToString();
                    parentNode.Nodes.Add(childNode);
                }
            }
        }
0
 
LVL 13

Expert Comment

by:dungla
ID: 18862116
You need to add all parent nodes as my first post already said. So your tree view will look like:

- Parent1
- Parent2
- Parent3

Then now we will make a for loop to add child for each parent node as my code above.

So take a look at your code, I can't see any code to add parent node, just create a Top Level is not enough. You know, we need to look up child by ParentUID retrieve from Tag property of Node.

I think the code will be something like that:

DataTable dtbParent = new DataTable(); // select from database.
foreach (DataRow drowParent in dtbParent.Rows)
{
TreeNode parentNode = new TreeNode();
parentNode.Text = drowParent["Name"].ToString();
parentNode.Tag = drowParent["ParentUID"].ToString();
treeView1.Nodes.Add(parentNode);
}
// now will have added all parent node, continue to add child
DataTable childTable = new DataTable();
childTable = ds.Tables[0];
foreach (TreeNode parentNode in treeView1.Nodes)
{
int intParentUID = Convert.ToInt32(parentNode.Tag);
DataRow[] dRowChildren = childTable.Select("ParentUID = " + intParentUID);
foreach (DataRow dRowChild in dRowChildren)
{
TreeNode childNode = new TreeNode();
childNode.Text = dRowChild["cat_name"].ToString();
parentNode.Nodes.Add(childNode);
}
            }
0
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 18863490
Ok, that's now populating the entire thing with all the data, but it's not all correct...

Currently, it's coming out like this:

Top Level
- Top Level
Site D
- Site D
- Site C
- Site B
- Site A
Site C
- Site D
- Site C
- Site B
- Site A

etc...

Here is an example of the data from the database:


UID       ParentUID       Name       displayorder
1       0       Top Level       0
2       1       Site A       0
3       1       Site B       0
4       2       Building A       0
5       1       Site C       0
6       1       Site D       0
7       5       Building B       0
8       5       Building C       0
9       4       Ground Floor       0
10       4       First Floor       0
11       9       Room A       0
12       11       Server A       0
13       12       Device A       0
14       12       Device B       0
15       13       Port 1       0
16       13       Port 2       0
17       13       Port 3       0
18       13       Port 4       0
19       14       Port 1       0
20       14       Port 2       0
21       14       Port 3       0
22       14       Port 4       0




Here is how the code looks at the moment:



private void PopulateTreeView1()
        {
            MySqlConnection conn = new MySqlConnection(connString);
            DataSet ds = new DataSet();
            conn.Open();
            MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM tblNavigator ORDER BY ParentUID, displayorder", conn);
            adapter.Fill(ds);
            conn.Close();

            TreeNode treeTopLevel;

            DataTable dtbParent = new DataTable();
            dtbParent = ds.Tables[0];
            foreach (DataRow drowParent in dtbParent.Rows)
            {
                TreeNode parentNode = new TreeNode();
                parentNode.Text = drowParent["Name"].ToString();
                parentNode.Tag = drowParent["ParentUID"].ToString();
                treeView1.Nodes.Add(parentNode);
            }

            DataTable childTable = new DataTable();
            childTable = ds.Tables[0];

            //treeTopLevel = treeView1.Nodes.Add("Top Level");

            foreach (TreeNode parentNode in treeView1.Nodes)
            {
                int intParentUID = Convert.ToInt32(parentNode.Tag);
                DataRow[] dRowChildren = childTable.Select("ParentUID = " + intParentUID);
                foreach (DataRow dRowChild in dRowChildren)
                {
                    TreeNode childNode = new TreeNode();
                    childNode.Text = dRowChild["Name"].ToString();
                    parentNode.Nodes.Add(childNode);
                }
            }
        }
0
 
LVL 5

Accepted Solution

by:
Yttribium earned 500 total points
ID: 18870719
Here's a working solution as far as I can see:

            private void PopulateTreeView1()
            {
                  int ParentUID = 0;
                  System.Collections.ArrayList tnodes = new System.Collections.ArrayList();
                  MySqlConnection conn = new MySqlConnection(connString);
                  DataSet ds = new DataSet();
                  conn.Open();
                  MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM tblNavigator ORDER BY ParentUID, displayorder", conn);
                  adapter.Fill(ds);
                  conn.Close();

                  DataTable dtbParent = new DataTable();
                  dtbParent = ds.Tables[0];

                  foreach (DataRow drowParent in dtbParent.Rows)
                  {
                        ParentUID = (int)drowParent["ParentUID"];
                        //If top node
                        if (ParentUID == 0)
                        {
                              TreeNode node = new TreeNode();
                              node.Text = drowParent["cat_name"].ToString();
                              node.Tag = (int)drowParent["UID"];
                              treeView1.Nodes.Add(node);
                              tnodes.Add(node);
                        }
                        else
                        {
                              for (int i = 0; i < tnodes.Count; i++)
                              {
                                    if ((int)((TreeNode)tnodes[i]).Tag == ParentUID)
                                    {
                                          TreeNode node = new TreeNode();
                                          node.Text = drowParent["cat_name"].ToString();
                                          node.Tag = (int)drowParent["UID"];
                                          tnodes.Add(node);
                                          ((TreeNode)tnodes[i]).Nodes.Add(node);
                                          break;
                                    }
                                    //End of tree
                                    
                              }
                        }
                  }
            }
0
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 18871950
That did the trick perfectly, thank you!!
0
 
LVL 5

Expert Comment

by:Yttribium
ID: 18872075
No probs
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now