Click here to Skip to main content
14,392,608 members

Binding Data With ‘TreeView’ Control 2.0

Rate this:
4.33 (34 votes)
Please Sign up or sign in to vote.
4.33 (34 votes)
15 Jul 2005
This article deals with the integration of 2.0 TreeView Control with database

Author:             Danish Hameed
Date:                15-July-2005
E-mail:             <st1:personname w:st="on">
Position:          Software Enginner

Programming Language: Visual Studio 2005 Beta 2, C# (C-Sharp)<o:p>

Author’s Introduction<o:p>

Danish Hameed is a Bachelor’s of science in computer science. He has participated and scored remarkable positions in programming and software competitions. Currently working as Software Engineer in eLearning industry.<o:p>

Binding Data With ‘TreeView’ Control 2.0<o:p>

<o:p> Over the period of few weeks I have been trying to play with 2.0 controls. As most of 2.0 beginners know there are almost no working examples and tutorials available for beta release and honestly I haven’t found people working on 2.0 so far as much as I expected.<o:p>

Now the real thing started when I decided to pick up some pace and started using Microsoft visual studio 2005 2.0 instead of VS’s prior version.Among so many new tools the one which I found really fascinating in 2.0 is TreeView control, the reason is; I have been creating TreeViews on JavaScript and had really tough time integrating them with server requests/responses.<o:p>

Introduction of TreeView Control<o:p>

A tree view control displays a hierarchical list of items using lines to connect related items in a hierarchy. Each item consists of a label and an optional bitmap. Windows Explorer uses a tree view control to display directories. It displays a tree structure, or menu, that users can traverse to get to different pages in your site. A node that contains child nodes can be expanded or collapsed by clicking on it.<o:p>

You can use ASP.NET site Navigation features to provide a consistent way for users to navigate your site. A simple solution is to include hyperlinks that allow users to jump to other pages, presenting the hyperlinks in a list or a navigation menu. However, as your site grows, and as you move pages around in the site, it quickly becomes difficult to manage all of the links.<o:p>

To create a consistent, easily managed navigation solution for your site, you can use ASP.NET site navigation TreeView control.

Fig: 1.0<o:p>

Image 1 <o:p>

Note: you can manually populate this control by,
1)     Clicking on TreeView control.
2)     Right click à Edit Nodes
3)     Under ‘Nodes’ heading there are two buttons, to add Parent and child nodes respectively.<o:p>

Lets do some work now!<o:p>

Now that we have pretty clear understanding of TreeView control, we will quickly move on and integrate this control with our site.<o:p>

Step 1<o:p>

Create two database tables ParentTable and ChildTable, having 2 columns each.<o:p>

ParentTable   à [ParentName , ParentId (as PK)]
ChildTable      à [ChildName , ParentId (as FK)]<o:p>

Note: you can use any database, in our example we will use Microsoft SQL server.<o:p>

Fig. 2.0<o:p>

<o:p>Image 2

Step 2<o:p>

Now that we have created our tables, open Microsoft Visual Studio 2005 and create and 2.0 WebForm.<o:p> 

Note: You can do this by clicking File menu and then New web site.
While creating the new page do not uncheck Place code in separate file checkbox.<o:p>

Step 3<o:p>

Add the following LOC (Line of code) at the start of your programs along with other using keywords.<o:p>

<o:p> using System.Data.SqlClient;<o:p>

Step 4<o:p>

Place a TreeView control on your WebForm.<o:p>

Note: Do not change its name, for simplicity we will use the default name TreeView1.<o:p>

Now double click your page, point to Page_Load event and write fill_Tree();

protected void Page_Load(object sender, EventArgs e)

Do not worry, we will use this function in next step.<o:p>

Step 5<o:p>

Now the real thing starts. In this step we will populate our TreeView1 control using our two tables ParentTable and ChildTable.

Create a function fill_Tree()<o:p>

void fill_Tree()<o:p>

* Fill the treeview control Root Nodes From Parent Table
* and child nodes from ChildTables

* Create an SQL Connection to connect to you our database

SqlConnection SqlCon = new SqlConnection("server=D_hameed;uid=sa;pwd=airforce;database=test");<o:p>


* Query the database

SqlCommand SqlCmd = new SqlCommand("Select * from ParentTable",SqlCon);<o:p>

*Define and Populate the SQL DataReader

SqlDataReader Sdr = SqlCmd.ExecuteReader();<o:p>

* Dispose the SQL Command to release resources

SqlCmd.Dispose ();<o:p>

* Initialize the string ParentNode.
* We are going to populate this string array with our            ParentTable Records
* and then we will use this string array to populate our TreeView1 Control with parent records

string[,] ParentNode = new string[100, 2];<o:p>

* Initialize an int variable from string array index

int count = 0;<o:p>

* Now populate the string array using our SQL Datareader Sdr.

* Please Correct Code Formatting if you are pasting this code in your application.

while (Sdr.Read())

ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("ParentID")).ToString();
ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("ParentName")).ToString();<o:p>


* Close the SQL datareader to release resources


* Now once the array is filled with [Parentid,ParentName]
* start a loop to find its child module.
* We will use the same [count] variable to loop through ChildTable
* to find out the number of child associated with ParentTable.

for (int loop = 0; loop < count; loop++)<o:p>


* First create a TreeView1 node with ParentName and than
* add ChildName to that node

            TreeNode root = new TreeNode();
            root.Text = ParentNode[loop, 1];
            root.Target = "_blank";<o:p>

* Give the url of your page

      root.NavigateUrl = "mypage.aspx";<o:p>

* Now that we have [ParentId] in our array we can find out child modules<o:p>

* Please Correct Code Formatting if you are pasting this code in your application.<o:p>


SqlCommand Module_SqlCmd = new SqlCommand("Select * from ChildTable where ParentId =" + ParentNode[loop, 0], SqlCon);<o:p>

SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();<o:p>

            while (Module_Sdr.Read())

// Add children module to the root node<o:p>

                TreeNode child = new TreeNode();<o:p>

                child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString();<o:p>

                child.Target = "_blank";<o:p>

                child.NavigateUrl = "your_page_Url.aspx";<o:p>



<o:p>             Module_Sdr.Close();<o:p>

<o:p> // Add root node to TreeView


* By Default, when you populate TreeView Control programmatically, it expends all nodes.


<o:p> Lets see how it looks like!<o:p>

<o:p> Fig. 3.0<o:p>

<o:p> Image 3

<o:p> You can spice it a bit by playing with [autoformat] and [show lines] property.<o:p>

<o:p> I will be extremely honored to get feedback from you.<o:p>

<o:p> By, Danish Hameed<o:p>


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
Pakistan Pakistan
No Biography provided

Comments and Discussions

QuestionThanks Pin
ntv870616-Jul-12 9:27
Memberntv870616-Jul-12 9:27 
GeneralMy vote of 5 Pin
ntv870616-Jul-12 9:25
Memberntv870616-Jul-12 9:25 
GeneralMy vote of 3 Pin
manoharnch20-Nov-11 22:44
Membermanoharnch20-Nov-11 22:44 
QuestionBinding Data With ‘TreeView’ Control 2.0[^] Pin
vsaranya10-Oct-11 20:20
Membervsaranya10-Oct-11 20:20 
GeneralMy vote of 5 Pin
Paul Lannuier20-Jul-11 12:49
MemberPaul Lannuier20-Jul-11 12:49 
GeneralMy vote of 5 Pin
Member 800720817-Jun-11 11:28
MemberMember 800720817-Jun-11 11:28 
GeneralMy vote of 5 Pin
gundakumar26-Apr-11 21:04
Membergundakumar26-Apr-11 21:04 
General5 years later and it's still a problem! Pin
Thesisus6-Dec-10 15:53
MemberThesisus6-Dec-10 15:53 
GeneralMy vote of 5 Pin
ammar11024-Nov-10 1:29
Memberammar11024-Nov-10 1:29 
GeneralMy vote of 4 Pin
Ahmed Eid Mohamed29-Aug-10 14:02
MemberAhmed Eid Mohamed29-Aug-10 14:02 
QuestionBut how to add subnodes's nodes...and so on.. Pin
igaurav10-Jun-09 22:28
Memberigaurav10-Jun-09 22:28 
QuestionPlease help Pin
joshualee5-May-09 15:57
Memberjoshualee5-May-09 15:57 
Generalsmall doubt abt this articcle Pin
112233jeeva2-Mar-09 1:01
Member112233jeeva2-Mar-09 1:01 
Generalthanks Pin
jayavayal10-Feb-09 22:36
Memberjayavayal10-Feb-09 22:36 
GeneralGreat Article, I need some more Help Pin
kasimmohamed26-Nov-08 1:13
Memberkasimmohamed26-Nov-08 1:13 
GeneralDisplay items of list box in Tree view format Pin
Good Speed10-Mar-08 22:01
MemberGood Speed10-Mar-08 22:01 
Questionadding depth to treeview upto four level Pin
NetKing10-Mar-08 6:42
MemberNetKing10-Mar-08 6:42 
QuestionRe: adding depth to treeview upto four level Pin
Bufnita Worth8-Aug-08 9:32
MemberBufnita Worth8-Aug-08 9:32 
GeneralSub Nodes in Tree Node Control [modified] Pin
Naveen Kumar.M2-Mar-08 21:25
MemberNaveen Kumar.M2-Mar-08 21:25 
GeneralRegarding treeview permission Pin
Member 390017221-Dec-07 0:28
MemberMember 390017221-Dec-07 0:28 
GeneralPlease upload the code for your project Pin
rama charan4-Dec-07 4:07
Memberrama charan4-Dec-07 4:07 
Generalpassing parameters from treeview node Pin
Kumar Padma6-Sep-07 0:50
MemberKumar Padma6-Sep-07 0:50 
GeneralAdding depth to tree Pin
Kumar Padma6-Sep-07 0:46
MemberKumar Padma6-Sep-07 0:46 
GeneralRe: Adding depth to tree Pin
sendtovishaljain4-Nov-08 5:05
Membersendtovishaljain4-Nov-08 5:05 
GeneralRe: Adding depth to tree Pin
karm1233-Jun-10 2:07
Memberkarm1233-Jun-10 2:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 15 Jul 2005


1 download
66 bookmarked