Monday, October 8, 2012

TreeView Control Example

 

In this article i will illustrate how to use treeview control.

TreeView Control allows to create a multi level navigation menu.

Create the menu items that treeview has to display in an XML file. Then bind this XML file to treeview control.

1)Create XML file with the menu items.

<?xml version="1.0" encoding="utf-8" ?>
<MyHomepage>
    <Menu Name="About Us">
        <SubMenu Title="History"></SubMenu>
        <SubMenu Title="Our Services"></SubMenu>
        <SubMenu Title="Our Products"></SubMenu>       
    </Menu>
    <Menu Name="Gallery">
        <SubMenu Title="Photos"></SubMenu>
        <SubMenu Title="Videos"></SubMenu>       
    </Menu>
    <Menu Name="Contact Us">
        <SubMenu Title="Phone"></SubMenu>
        <SubMenu Title="Email"></SubMenu>
    </Menu>
</MyHomepage>

Create an aspx page named “TreeView.aspx” and then Now drag and drop TreeView Control and XmlDataSource Controls. Assign Xml file path to “DataFile” attribute of “XmlDataSource” . Then Assign “XmlDataSource” ID to “DataSourceID” attribute of “TreeView” Control.

Specify the databindings as follows and execute it.

<form id="form1" runat="server">
   <div>
       <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="XMLFile.xml">
       </asp:XmlDataSource>
       <asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1">
       <DataBindings>
           <asp:TreeNodeBinding DataMember="MyHomepage" Text="My WebSite" />
           <asp:TreeNodeBinding DataMember="Menu" TextField="Name" />
           <asp:TreeNodeBinding DataMember="SubMenu" TextField="Title" />
       </DataBindings>
       </asp:TreeView>
   </div>
   </form>

Output:

Treeview1

1 comment: