TreeView Navigation in ASP.Net 2.0 - Treeview DataSource Binding
(Page 4 of 5 )
There are two types of TreeView xml binding: XmlDataSource and SiteMapDataSource. The XmlDataSource allows you to define complex XM for your menu; the SiteMapDataSource gives you the benefit of a pre-defined XML schema.
Binding to an XmlDataSource
There are two major advantages to using an XmlDataSource. First, your can change the XML file without interrupting the rest of the code. The declarative TreeView required editing of the web form. Second, you can create complex menu structures with relatively little code.
There are three components to the TreeView that is mapped to an XmlDataSource:
- the TreeView
- a datasource
- the menu data in an xml file
The datasource is the connection between the TreeView and the XML data. The TreeView points to ds_xml datasource, and the ds_xml datasource points to the therapuppy.xml file containing the menu. See Figure 8.
Figure 8: The TreeView binds to the datasource which references the xml menu

So what is the form of the XML menu file? For our menu it can be any valid XML that names the anchor text and navigation URL. Let’s just make one up (see Figure 9):
Figure 9: The XmlDataSource file can have any valid xml

So if we made up our own XML schema, what will we get running this code? How does the TreeView know what the menu, name and URL fields are? Right now, it doesn’t know what they are. It finds valid XML and binds to it in TreeView fashion:
Figure 10: No connection between the TreeView and its Bindings

We’ll fix this by telling the TreeView how to interpret the XML file. We use the DataBindings mechanism. See Figure 11.
We need to define two fields: the menu anchor text and the navigation URL. In our XML file, these are the name and url attributes of the menu nodes.
So we create a DataBinding that maps the menu name to our anchor text and the menu url to our anchor URL. Again, see Figure 11.
Figure 11: The DataBinding element goes inside the TreeView definition.

Now the TreeView binds the data in those fields to the TreeView, to render an almost correct menu (figure 12):
Figure 12: The TreeNodeBinding Provides Anchor Text and Url

The problem, of course, is the word “root” at the top of our menu. One way to deal with this is to define an XPath statement in datasource. A simple one would instruct the TreeView to navigate to the second level of data in the XML source (figure 13).
Figure 13: XPath Limits TreeView Display


The XPath could also be expressed as “everything at the menu level,” as we want to display all of the menu items and their menu children: XPath="/root/menu."
Next: Binding to a SiteMapDataSource >>
More ASP.NET Articles
More By Caroline Bogart