Populating a TreeView Control using Recursion

Download Code File source

 Introduction:

The Tree View control is an object which allows creation of nodes dynamically. It will have the Root, Parent and Leaf. The Tree View control has properties and events.

It has some characteristics.

  • Tree View node can navigate to some other pages
  • The images and properties can be set to the nodes
  • It can have the lines, check box and images
  • It can set dynamically expand/collapse
  • The nodes can be created on demand 

Description:

In this article I show you how to populate a tree view control using c# using a data table. 

How Application works:

I used only two buttons. The user on pressing the connection button on the form allows the program to bridge a connection between the database and the application. Within the program I preferred connection less approach. (Fig-1)

Fig-1
Fig-1

Once connection is established on pressing the show tree button the code which I will explaining in next section, populate the tree view Control using data table. (Fig-2)

Figure-2
Fig-2

How code works:

Building Connection with Database (Fig-3)

Fig-3
Fig-3

I used Sqlconnection, Sqlcommand, SqlAdapter and Dataset classes to build a connection with the Database to fetch the data table. Pressing connection button the event behind this button ‘Button1_Click’ is called which establishes the connection with the database and get the data table of the city list shown in (Fig-4)

Fig-4
Fig-4

 In the above data table each name will represent a node in the tree view control.Each node has a column parent id and a column of its own id.

Sql command to get table:

fig-5
Fig-5 

Now you see the show tree button event in which I create a tree node object and call the fill tree function which will eventually populate the tree.

Fig-6
Fig-6

The function is given three parameter

1-   Tree node object

2-   Id of the node

3-   And the data table which contains the table shown in fig-4

then I added the node in tree view control using treeview.Nodes.Add (node) and table in data grid view control.

Fill tree Method:

Fig-6
Fig-7

Fill tree method takes three arguments and create nodes in recursive manner until the point is reached where no child exists for the current node. Then eventually it return and we have a complete hierarchy as shown in figure-2.

Author

Mohsin Ali

Computer Science Department

Govt. College University Lahore, Pakistan