TreeView allows to display the data in a hierarchical format. There are many different ways of populating a TreeView control which includes SiteMap files, XML files and custom entity collections. In this article we will demonstrate how to populate the TreeView control using different sources. We will also demonstrate how to hide the root node of the TreeView control when using custom collection.
Populating TreeView Control Using Sitemap Files:
Sitemap was introduced in ASP.NET 2.0 which helped the developers to create and configure the navigation of the website. TreeView control can easily utilize the sitemap file and display the contents in a hierarchical format. In the implementation below we have created a very simple sitemap file:
The sitemap file consists of two nodes. Each node points to a search engine link which in this case are "Google" and "Yahoo". The following code is used to populate the TreeView control with the sitemap contents.
One thing to notice about the SiteMapDataSource control is that we have indicated that we do not want to show the root node. This is achieved by setting the "ShowStartingNode" property to false. The screenshot belows shows that the root node is excluded from the TreeView and only the child nodes are displayed.
Populating TreeView Control Using XML File:
If you display a TreeView control whose source does not change often then XML file might be your best bet. The reason is that you can always create a cache dependency on the XML file which means the file is loaded from the cache unless the it is changed. The XML file for this demo is shown below:
As you can see the XML file consists of multiple categories and each category consists of multiple products. The implementation below is used to populate the TreeView control.
The result is shown in the screenshot below:
The screenshot shows that the root node is displayed on the page. In most applications we do not want the root node to appear on the page. You can use the XPath expression to hide the root node. The modified XmlDataSource control is shown below:
The XPath expression is used to extract all the category items out of the XML file. The root node is discarded since the XPath is only looking for category items.
Populating TreeView Control Custom Entity Collection:
The code above goes through the TreeView control and hides the anchor tag which contains the image for the root node. For this to work you must make sure that the TreeView is not collapsed or else the jQuery will not be able to display child nodes.
In this article we learned different ways for populating the TreeView control. We also learned how to hide the root element of the TreeView control.