12,695,183 members (31,362 online)
alternative version

22.9K views
13 bookmarked
Posted

# Building a dynamic Tree

, 22 Sep 2007 CPOL
 Rate this:
You want to buid a dynamic menu!? You can use recursive algorithm to solve this.

## Introduction

When you build a application or website, you want to build a dynamic menu with many level depend on your categoris, sub-categories, products but you have never ever known exactly the number of level of your menu. Now, I make this one to show you the way to solve this problem.

## Background

When you have to make a website of the shop. This shop have many product and they want to arrange their product to category, sub-category, product to many many level. They want to make it dynamic, they can make a new level (sub-sub-category,..) and you have to let them do that. When you develope, you don't know that how many level of menu could be builded.

To slove this problem, you should use resursive algorithm.

Here, I use TreeView in WinForm to demo this. I will read data in a Datatable to build a dynamic tree. This code can be used in ASP.NET. I use Visual Studio 2005 to develope it.

## Using the code

First, I will define a DataTable to store the ID, PID(parent ID), Info of the menus...
```//
//  ```
``` ```
```DataTable tbl;
DataColumn col;
private void InitTable()
{
tbl = new DataTable();

col = new DataColumn("ID");
col = new DataColumn("PID");
col = new DataColumn("Info");

tbl.AcceptChanges();
}
```

Then, I will make the data for this table. This table is store the information of menus.

```//
private void initTableData()
{
DataRow r;

r = tbl.NewRow();
r["ID"] = "0";
r["PID"] = "-1";
r["Info"] = "Root";

r = tbl.NewRow();
r["ID"] = "1";
r["PID"] = "0";

r = tbl.NewRow();
r["ID"] = "10";
r["PID"] = "0";

r = tbl.NewRow();
r["ID"] = "2";
r["PID"] = "0";

r = tbl.NewRow();
r["ID"] = "3";
r["PID"] = "0";

r = tbl.NewRow();
r["ID"] = "4";
r["PID"] = "1";

r = tbl.NewRow();
r["ID"] = "5";
r["PID"] = "4";

r = tbl.NewRow();
r["ID"] = "6";
r["PID"] = "5";

r = tbl.NewRow();
r["ID"] = "7";
r["PID"] = "2";

r = tbl.NewRow();
r["ID"] = "11";
r["PID"] = "6";

r = tbl.NewRow();
r["ID"] = "8";
r["PID"] = "10";

r = tbl.NewRow();
r["ID"] = "9";
r["PID"] = "3";

r = tbl.NewRow();
r["ID"] = "12";
r["PID"] = "7";
}
// ```

Let's start to build the tree!

I make a method to build this tree. This tree has a "Root" with ID=0 and PID=-1. So that, any menu has PID=0 is a child of this menu and this "Root" with PID=-1 has no parent.

We will add this "Root" to the tree and call the method initTreeView(TreeNode N). We consider that all sub menu is a TreeNode and we will add this TreeNode to "Root". With another Node, we continue to consider it a "mini root" and another menu which are children of this node is a "mini node" so we will add to this "mini root" then, too.

```private void initTreeView(TreeNode N)
{
DataTable temp = new DataTable();
col = new DataColumn("ID");
col = new DataColumn("PID");
col = new DataColumn("Info");
temp.AcceptChanges();

string id = getID(N);
foreach (DataRow r1 in tbl.Rows)
{
if (r1["PID"].ToString() == id)
{
DataRow r2 = temp.NewRow();
r2["ID"] = r1["ID"].ToString();
r2["PID"] = r1["PID"].ToString();
r2["Info"] = r1["Info"].ToString();
temp.AcceptChanges();
}
}

foreach(DataRow r3 in temp.Rows)
{
TreeNode tn = new TreeNode();
tn.Text = r3["Info"].ToString();
initTreeView(tn);
}
}
```

With any node, we will find all of its children (I define a new DataTable: temp to store those children), with each children will continue to call the method initTreeView() to build it. So on, so on, we will find the smallest menu and add it to its parent.

## Points of Interest

With a short of code, we have builded a dynamic menu. It is simple to make, easy to remember and can be apply to WinForm or WebForm.
This algorithm could be use to any language.

Enjoy with my code! Thanks for reading!

Name: Nguyen Anh Vu
Email: nguyenanhvu.aiti@gmail.com
or spiderman_anhvu@yahoo.com

## Share

 Web Developer Vietnam
No Biography provided

## You may also be interested in...

 Pro Pro

 First Prev Next
 Nice try but... ESTANNY25-Sep-07 2:20 ESTANNY 25-Sep-07 2:20
 Something is not quiet right in your application.When you have 2 menuitems with the same name, it will go wrongI think that the problem is when you call the following:private string getID(TreeNode N) { foreach (DataRow r in tbl.Rows) { if (r["Info"].ToString() == N.Text) return r["ID"].ToString(); } return ""; } What I do is use the Node.Tag to store the ID, so you can run through your whole tree to find the node.tag = pidMy get parent node is here (in VB, but it should be easy to convert it to C#)```Private Function GetParentNode(ByVal pid As String, ByVal pn As TreeNode) As TreeNode If (pn.Tag.Equals(pid)) Then Return pn End If For Each node As TreeNode In pn.Nodes Dim n As TreeNode = GetParentNode(pid, node) If (Not n Is Nothing) Then Return n End If Next End Function```My part of the function to populate the treeview: (i have 4 columns, a type column that can be used to distinguish different node types, like folder, root, profile... And it is stored in an DB)```For Each r As DataRow In dt.Rows ' r(0) = id ' r(1) = pid ' r(2) = name ' r(3) = type: Folder, Root, Profile ' ImageIndex Root = 0 ' ImageIndex Folder = 1 ' ImageIndex Profile = 2 If (r(1).ToString = "0") Then ' Add Root node Dim node As New TreeNode node.Text = r(2).ToString node.Tag = r(0).ToString Me.TreeView1.Nodes.Add(node) Else ' Find the parent node For Each root As TreeNode In TreeView1.Nodes Dim node As TreeNode = GetParentNode(r(1).ToString, root) If (Not node Is Nothing) Then Dim n As New TreeNode n.Text = r(2).ToString n.Tag = r(0).ToString If (r(3).ToString.Equals("Root")) Then n.ImageIndex = 0 ElseIf (r(3).ToString.Equals("Folder")) Then n.ImageIndex = 1 ElseIf (r(3).ToString.Equals("Profile")) Then n.ImageIndex = 2 End If node.Nodes.Add(n) node = Nothing Exit For End If Next End If Next```Good luck!
 Last Visit: 31-Dec-99 19:00     Last Update: 19-Jan-17 4:33 Refresh 1