DataTable to TreeView in C#, Displaying Hierarchies

In this article I will show you how to display hierarchies in a TreeView control, when your data is in a DataTable. In this example we have an Employee table with 3 columns: ID, ParentID and Name.
ParentID is the ID of the boss for the current Employee.

The first step is to sort the table by the ParentID. This step is really important because we cannot insert a node in the tree until it's parent is not inserted. Notice the root of the tree having a ParentID of -1.

Here is the code for this:

The second step is to use a XmlDocument. The TreeView control does not have the functionality to find an arbitrary node given a node ID. A recursive find function seems to be too much hassle, not to mention the performance, so I decided to take advantage of the XPath search capabilities of XmlDocument to find a given Parent node.

Here is the code for this:

The third step is to hook up our data to the TreeView. If you try to bind the TreeView control to an XmlDocument you will get this error: HierarchicalDataBoundControl only accepts data sources that implement IHierarchicalDataSource or IHierarchicalEnumerable. To resolve this we can use an XmlDataSource control.

Here is the code for this:

Done. I hope that my little guide helped you in a way.
Your comments are welcomed.
Happy coding :)


Popular posts from this blog

14 Sfaturi pentru programatori incepatori

Sanitizer provider is not configured in the web.config file. Ajax Control Toolkit and HtmlEditorExtender problems.