Tuesday, April 22, 2008 10:17 PM
UPDATE: (14/10/2008) Thank you for everybody who has commented on this post and given me valuable feedbacks.
I have updated the C# code to include most of your comments/fixes.
Includes: Proper handling for null or empty column values as the parent columns and added subtree loading.
Thank you again.
The other day I wanted to bind a TreeView to a DataSet (or an ObjectDataSource that would return a DataSet) and I was disappointed to see that it does not support this. Googling this showed a lot of developers opting to fill the TreeView themselves programmatically. So I decided to create a simpler solution for this.
The key to this solution is that the TreeView can bind to any object that implements the interface IHierarchicalDataSource. So I created a simple class that takes a DataSet as its input along with two column names, I will explain them in a moment, and this class would implement the IHierarchicalDataSource interface.
So instead of writing:
TreeView1.DataSource = dataSet;
which is not supported, we write this:
TreeView1.DataSource = new HierarchicalDataSet(dataSet, "ID", "ParentID");
Check this post for the VB.NET version of the sample application.
The two extra parameters that you have to pass to the constructor of HierarchicalDataSet are two column names. The first one being the primary key of the table, and the second one being the parent key which usually would be a foreign key to the primary key of the same table; this allows modeling the tree structure in a database table. Here is a simple design of such a table.