Part 162 Binding asp net treeview control to database table

  • دعنا نشارك هذا :
ترتيب الدرس : 162
المدة : 00:14:29
التحكم :
Link for code samples used in the demo

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

Link for all dot net and sql server video tutorial playlists

In this video, we will discuss binding treeview control to database table. This is continuation to Part 161, please watch Part 161 before proceeding.

1. Create the required database table using the script below.
Create table tblTreeViewItems
ID int identity primary key,
TreeViewText nvarchar(50),
NavigateURL nvarchar(50),
ParentId int references tblTreeViewItems(ID)

2. Create a stored procedure that returns data from tblTreeViewItems table.
Create proc spGetTreeViewItems
Select ID, TreeViewText, NavigateURL, ParentId
from tblTreeViewItems

3. Drag and drop a treeview control on the webform

4. Copy and paste the following code in the code-behind file.
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)

private void GetTreeViewItems()
string csConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection connew SqlConnection(cs);
SqlDataAdapter danew SqlDataAdapter("spGetTreeViewItems", con);
DataSet dsnew DataSet();

ds.Relations.Add("ChildRows", ds.Tables[0].Columns["ID"],

foreach (DataRow level1DataRow in ds.Tables[0].Rows)
if (string.IsNullOrEmpty(level1DataRow["ParentId"].ToString()))
TreeNode treeNodenew TreeNode();

DataRow[] level2DataRowslevel1DataRow.GetChildRows("ChildRows");
foreach (DataRow level2DataRow in level2DataRows)
TreeNode childTreeNodenew TreeNode();

Note: Please include the following using declarations.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

The above code works as expected only with 2 levels of TreeNode objects. If you include a third level, those TreeNodes will not be displayed in the TreeView control. For example, if you execute the following insert sql script. These rows will not be displayed in the TreeView control, we will discuss fixing this in our next video.
Insert into tblTreeViewItems values ('AAA', '~/AAA.aspx', 5)
Insert into tblTreeViewItems values ('BBB', '~/BBB.aspx', 5)

سيتم تفعيل التعليقات قريبا

Sep 23, 2020 07:32:27