Wednesday, February 4, 2009

Binding TreeView to Xml

If we want to display hierarchical data we have the possibility to use binding to an asp TreeView control.

To do this all we need to do is to set the DataSource property of the TreeView control to the data source, and then call the DataBind method. In our case the data source is a xml file that can look like this:

treeviewxml 

The result that we want should look like this :

treeviewxmlresult

To obtain this result we first have to add the ASP control to page and after that to add the code for data binding. Here is the html part for adding the control. I added an label also to display messages:

<body> 
<form id="form1" runat="server">
<div>
<asp:Label ID="ChapterLabel" Text="A tree for car classification:" runat="server" ></asp:Label>
<asp:TreeView ID="ChapterTree" runat="server" ShowLines="true" >
</asp:TreeView>
</div>
</form>
</body>



To obtain the desired result as you see we have to create TreeNodeBinding objects that define the relation between data item and the node that it is binding to. Below is the code that do the job:




protected void Page_Load(object sender, EventArgs e) 
{
TreeView tv = (TreeView)Page.FindControl("ChapterTree");

// build the data source for the tree
XmlDocument theBigTree = BuildXmlTree();
XmlDataSource xmlds = new XmlDataSource();
xmlds.Data = theBigTree.InnerXml;
xmlds.DataBind();
TreeNodeBinding treeBinding = new TreeNodeBinding();
treeBinding.DataMember = "tree";
treeBinding.TextField = "name";
TreeNodeBinding nameBinding = new TreeNodeBinding();
nameBinding.DataMember = "node";
nameBinding.TextField = "name";
tv.DataBindings.Add(treeBinding);
tv.DataBindings.Add(nameBinding);
tv.DataSource = xmlds;
tv.DataBind();
}