In this article I will explain how to populate (bind) TreeView from SiteMap using SiteMapDataSource in ASP.Net.
The SiteMap file contains navigation information about a website and using the SiteMapDataSource we can easily populate the TreeView control.
 
HTML Markup
The HTML Markup consists of a TreeView control and a SiteMapDataSource. The Id of the SiteMapDataSource is set as the DataSourceID for the TreeView control.
<asp:TreeView ID="TreeView1" runat="server" ImageSet="Simple" NodeIndent="10" DataSourceID="SiteMapDataSource1">
    <HoverNodeStyle Font-Underline="True" ForeColor="#DD5555" />
    <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px"
        NodeSpacing="0px" VerticalPadding="0px"></NodeStyle>
    <ParentNodeStyle Font-Bold="False" />
    <SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px" VerticalPadding="0px"
        ForeColor="#DD5555" />
</asp:TreeView>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="false" />
 
 
Adding the Sitemap XML and understanding its use
Sitemap is nothing but a map of your site, it is an XML files which has all the Pages and the Child Pages present in the site. Whenever a new page has to be added to your site, you simply need to add its node in the sitemap XML file and the ASP.Net Menu control will automatically grab and display it.
Sitemap can be added using Add New Item Dialog of Visual Studio as shown below.
 
Populate (Bind) TreeView from SiteMap using SiteMapDataSource in ASP.Net
 
Once the file is added you need to structure it based on the Level 1 Pages and the Child Pages.
Note: You can have as many child levels as you want, here I am using 2 Level Menu structure
 
Below is the sitemap I am using for this article, it has the following page structure.
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
 <siteMapNode url="" title="Homedescription="">
    <siteMapNode url="Home.aspx" title="Homedescription="Home Page" />
    <siteMapNode url="javascript:;" title="Servicesdescription="Services Page">
      <siteMapNode url ="Consulting.aspx" title="Consulting" description="Consulting Page"></siteMapNode>
      <siteMapNode url ="Outsourcing.aspx" title="Outsourcing" description="Outsourcing Page"></siteMapNode>
    </siteMapNode>
    <siteMapNode url="About.aspx" title="About" description="About Us Page" />
    <siteMapNode url="Contact.aspx" title="Contact" description="Contact Us Page" />
 </siteMapNode>
</siteMap>
 
That’s all you need to do and the run the project and you will see the TreeView control displaying the contents of the SiteMap as shown below.
Populate (Bind) TreeView from SiteMap using SiteMapDataSource in ASP.Net
 
 
Demo
 
Downloads