Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

Home

Categories
Forums
Contact
Search

Populate (Bind) TreeView from database in ASP.Net

23 Aug 2014 Mudassar Khan 0 Comments 44201 Views


ASP.Net SQL Server TreeView

Follow @ASPSnippets

Here Mudassar Ahmed Khan has explained how to populate or bind TreeView from database in
ASP.Net using C# and VB.Net.

Download View Demo

Download FREE API to handle Office files, it really helps - http://e-iceblue.com/free-api


In this article I will explain how to populate or bind TreeView from database in ASP.Net using C#
and VB.Net.

The TreeView will be populated using recursion.


Database

In order to populate TreeView with Parent Child relationship, I have made use of two tables
namely VehicleTypes and VehicleSubTypes. The schema and the data present in both the tables are
as follows.

VehicleTypes

VehicleSubTypes

Note: The
SQL for
creating the
database is
provided in the
attached sample
code.

HTML Markup

The HTML Markup consists of an ASP.Net TreeView.

<h3>
Vehicle Details</h3>
<hr />
<asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black"
HorizontalPadding="2px"
NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False"
HorizontalPadding="0px"
VerticalPadding="0px" />
</asp:TreeView>

Namespaces

You will need to import the following namespaces.

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.Net

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Populating TreeView from database

The PopulateTreeView method is a recursive function. Inside the Page Load event, the TreeView
is populated with the records from the VehicleTypes table.

Inside the PopulateTreeView method, a loop is executed over the DataTable and if the ParentId is
0 i.e. the node is a parent node, a query is executed over the VehicleSubTypes table to populate the
corresponding child nodes and again the PopulateTreeView method is called.

This process continues until all parent nodes along with their child nodes are added to the
TreeView.

C#

protected void Page_Load(object sender, EventArgs e)


{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT Id, Name FROM VehicleTypes");
this.PopulateTreeView(dt, 0, null);
}
}

private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)


{
foreach (DataRow row in dtParent.Rows)
{
TreeNode child = new TreeNode
{
Text = row["Name"].ToString(),
Value = row["Id"].ToString()
};
if (parentId == 0)
{
TreeView1.Nodes.Add(child);
DataTable dtChild = this.GetData("SELECT Id, Name FROM VehicleSubTypes WHERE
VehicleTypeId = " + child.Value);
PopulateTreeView(dtChild, int.Parse(child.Value), child);
}
else
{
treeNode.ChildNodes.Add(child);
}
}
}

private DataTable GetData(string query)


{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load


If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData("SELECT Id, Name FROM VehicleTypes")
Me.PopulateTreeView(dt, 0, Nothing)
End If
End Sub

Private Sub PopulateTreeView(dtParent As DataTable, parentId As Integer, treeNode As


TreeNode)
For Each row As DataRow In dtParent.Rows
Dim child As New TreeNode() With { _
.Text = row("Name").ToString(), _
.Value = row("Id").ToString() _
}
If parentId = 0 Then
TreeView1.Nodes.Add(child)
Dim dtChild As DataTable = Me.GetData("SELECT Id, Name FROM VehicleSubTypes
WHERE VehicleTypeId = " + child.Value)
PopulateTreeView(dtChild, Integer.Parse(child.Value), child)
Else
treeNode.ChildNodes.Add(child)
End If
Next
End Sub

Private Function GetData(query As String) As DataTable


Dim dt As New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function

Demo
View Demo

Downloads

Download

Related Articles

Display Images from SQL Server Database using ASP.Net


Here Mudassar Ahmed Khan has explained how to retrieve and display images that are stored in
SQL Server Database in ASP.Net Web application
Comments

No comments have been added to this article.

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email
address
else you won't be notified when the author replies to your comment
Please note that all comments are moderated and will be deleted if they are
Not relavant to the article
Spam
Advertising campaigns or links to other sites
Abusive content.
Please do not post code, scripts or snippets.

Follow @ASPSnippets

Name
Email
Comment

Security code:
Add Comment
Subscribe

Follow @ASPSnippets

Subscribe
What our readers say

Paul Wilcox
Just wanted to say I enjoyed this. Javascript is not my strongest language so its nice to have some
code to look at and play around with. I was able to get this up and running pretty quickly. Thanks.

Subscribe

Please enter your email address:

2017 www.aspsnippets.com All


rights reserved | Privacy Policy |
Powered by Excelasoft Solutions

You might also like