Binding Site Map to Treeview
The TreeView
control supports declarative binding to a site-map file by using SiteMapDataSource
controls. When binding to an instance of the SiteMapDataSource control,
the Title
and Url
properties of each SiteMapNode
are automatically associated with the Text and NavigateUrl
properties of each TreeNode object in the TreeView control, so
there is no need to create custom data bindings.
Now create
a TreeView and assign a SiteMapDataSource that is already on the page:
//Code Behind
TreeView tv1 = new TreeView();
tv1.DataSourceID = "SiteMapDataSource1";
//aspx
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
Binding a Site Map to Treeview Programmatically
Or you can
assign the SiteMap programmatically:
// Create an instance of the
XmlSiteMapProvider class.
XmlSiteMapProvider testXmlProvider
= new XmlSiteMapProvider();
System.Collections.Specialized.NameValueCollection
providerAttributes
= new
System.Collections.Specialized.NameValueCollection(1);
providerAttributes.Add("siteMapFile", "Web2.sitemap");
// Initialize the provider with a provider
name and file name.
testXmlProvider.Initialize("testProvider",
providerAttributes);
// Call the BuildSiteMap to load the site map
information into memory.
testXmlProvider.BuildSiteMap();
SiteMapDataSource smd = new SiteMapDataSource();
smd.Provider = testXmlProvider;
TreeView tv2 = new TreeView();
tv2.DataSource = smd;
tv2.DataBind(); //Important or all is
blank
Setting
the SiteMap programmatically also allows you to switch files based on business
rules.
How
to add Sitemaps in web.config
This can
also be done via the Web.Config:
<configuration>
<!-- other configuration sections
-->
<system.web>
<!-- other
configuration sections -->
<siteMap>
<providers>
<add name="SiteMap1" type="System.Web.XmlSiteMapProvider" siteMapFile="~/Web.sitemap" />
<add name="SiteMap2" type="System.Web.XmlSiteMapProvider" siteMapFile="~/Web2.sitemap" />
</providers>
</siteMap>
</system.web>
</configuration>
and
then in your aspx page just switch provider:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="SiteMap2" />