Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Binding the ASP.NET TreeView to a DataSet or an ObjectDataSource

4.70/5 (17 votes)
2 May 2008CPOL1 min read 1   4.1K  
The TreeView can not bind to a DataSet or to an ObjectDataSource. With one line of code, you can do that now.

Introduction

The TreeView in ASP.NET is a powerful control that helps display hierarchical data. However, unlike other controls, it does not support binding to a DataSet or an ObjectDataSource. I have seen a lot of developers do this the old fashioned way, filling the tree programmatically, which is a waste of time and energy.

The Solution

The key to this solution is that the TreeView can bind to any object implementing the interface IHierarchicalDataSource. So, this article presents to you a small class that will take a DataSet as an input and return an object that implements IHierarchicalDataSource so that the TreeView can easily bind with your DataSets.

Under the Hood

The class HierarchicalDataSet presents data in a hierarchy, which means supports Parent-Child relationships, just like the nature of a TreeView control. You have nodes, and under some nodes, you have children. Creating this structure in a database involves having a table reference itself to implement the parent-child relationship. Here is how such a table would look like:

Table

Here is a quick example for some records to see how they will present the child parent relationship:

C#
DataRow row = dataSet.Tables[0].NewRow();
row["ID"] = 1;
row["Text"] = "Parent 1";
dataSet.Tables[0].Rows.Add(row);

row = dataSet.Tables[0].NewRow();
row["ID"] = 2;
row["Text"] = "Parent 2";
dataSet.Tables[0].Rows.Add(row);

row = dataSet.Tables[0].NewRow();
row["ID"] = 3;
row["ParentID"] = 1;
row["Text"] = "Child 1";
dataSet.Tables[0].Rows.Add(row);

row = dataSet.Tables[0].NewRow();
row["ID"] = 4;
row["ParentID"] = 1;
row["Text"] = "Child 2";
dataSet.Tables[0].Rows.Add(row);

row = dataSet.Tables[0].NewRow();
row["ID"] = 5;
row["ParentID"] = 2;
row["Text"] = "Child 3";
dataSet.Tables[0].Rows.Add(row);

row = dataSet.Tables[0].NewRow();
row["ID"] = 6;
row["ParentID"] = 2;
row["Text"] = "Child 4";
dataSet.Tables[0].Rows.Add(row);

Using the Code

Using the code is very simple. You need to call the constructor of the class that takes the DataSet and the two column names needed. The primary key and the foreign key reference the same table.

C#
TreeView1.DataSource = new HierarchicalDataSet(dataSet, "ID", "ParentID");

Hope this helps.

History

  • 2nd May, 2008: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)