About the TreeView WebControl

This article provides an introduction to authoring with the TreeView control, which facilitates the authoring of user interfaces that render hierarchical datasets, folder views, and other similar data structures. This control implements several powerful features, including support for data binding and rich Dynamic HTML (DHTML) behaviors in uplevel browsers. In most scenarios, a TreeView can be authored declaratively; however, this control can also be programmed extensively on the client or server.

This document includes the following sections.


The TreeView is an ASP.NET control for authoring user interfaces representing hierarchical data. As with the other Windows Internet Explorer WebControls, the TreeView control delivers HTML based on the browser type. In downlevel browsers, the page content sent by the TreeView ASP.NET controls is HTML 3.2, whereas, in uplevel browsers the HTML, pages also use DHTML behaviors, which are client-side components that define custom elements. With WebControls, an uplevel browser is Microsoft Internet Explorer 5.5 or later, and a downlevel browser is Internet Explorer 5.01 or earlier or a browser other than Internet Explorer.

This overview provides practical examples illustrating how to author and use the TreeView controls. The TreeView is one of four WebControls; therefore, in order to author Web pages with any of these controls, a similar set of prerequisites apply. For general information on the WebControls, including download and setup instructions, see Internet Explorer WebControls and Authoring Web Forms with the WebControls.

The WebControls are ASP.NET controls that include a set of DHTML behaviors, which provide an enhanced user experience in uplevel browsers. For each of the WebControls, a DHTML behavior exposes a client-side object model that closely corresponds to the server-side object model implemented by the ASP.NET control. The component architecture in Internet Explorer 5.5 and ASP.NET has distinct differences, and so the object model exposed by the client-side and server-side objects are slightly different.

The use of both client-side and server-side components means that two modes of authoring Web pages with the TreeView are possible. In ASP.NET, Web Forms can be written that deliver content based on the browser capabilities, using behaviors in uplevel browsers. These pages can make use of server-side script, which is written using one of the common language runtime languages. For Internet Explorer 5.5 or later versions, Web pages can be written that use the DHTML behavior with client-side script.


To make the best use of this article, you should be familiar with the basic types ASP.NET controls and know how to use them to author a simple Web Forms page. Some knowledge of browser scripting and DHTML behaviors is also required because the WebControls use behaviors in uplevel browsers.

The code samples in this article are given in C# and Microsoft Visual Basic .NET. Web developers should find the samples easy to understand, even if they are new to ASP.NET and the common language runtime.

For more information on setup requirements for hosting Web pages with ASP.NET and the WebControls, see the Internet Explorer WebControls.


Term Description
Web Forms The ASP.NET Web Forms Page Framework is a scalable common language runtime programming model that can be used to dynamically generate Web pages. Web Forms are .aspx files that are parsed and processed by ASP.NET. The WebControls are custom ASP.NET controls that are designed for authoring in the Web Forms environment.

TreeView Objects

This section outlines the basic similarities and differences between the client and server implementations of the TreeView. The TreeView Reference page provides links to the reference documentation for the client-side and server-side objects exposed by the TreeView components.

The TreeView control can also be authored visually using the TreeView Editor in Visual Studio .NET. This article focuses mainly on manual methods of building content with the TreeView. For more information on visual editing with the TreeView, see Using the TreeView Designer in Visual Studio .NET.

The TreeView can be authored declaratively, and it can also be programmed with script on the client or server. When authoring declaratively, the elements and attributes supported by the client and server components are very similar. Therefore, the declarative samples presented in this article work in Web Forms pages that use the ASP.NET TreeViewcontrols and in HTML pages that use the TreeView behavior.

Due to the differences in the programming languages supported in ASP.NET and Internet Explorer, separate reference documentation is provided for the client and server components.

ASP.NET Controls

The most comprehensive programming model for the TreeView is exposed by the ASP.NET controls. Using the ASP.NET controls is the recommended approach in scenarios where Web pages must function in a wide range of browsers. This is because the WebControls detect the browser type and deliver HTML 3.2 content to the downlevel browsers.

For more information, see the ASP .NET Server Controls Reference.

Client Behavior

For those who wish to optimize the client performance in Internet Explorer 5.5 or later versions, there is also a TreeView behavior. ASP.NET Web Forms using the WebControls automatically download the TreeView behavior to uplevel browsers. Therefore, the TreeView behavior can be used independently of ASP.NET when writing client-only HTML pages.

The TreeViews seen in many Windows applications often have rich features; for example, the nodes in a TreeView can by expanded or collapsed by using mouse or keyboard entry. The TreeView behavior supports all of these features, and data binding can be implemented in client or server-based Web pages.

TreeView Elements

The TreeView can be authored using a combination of one or more of the following elements, which are supported by the client-side and server-side TreeView components.

Element Name Description
TreeView Defines a TreeView.
TreeNodeType Defines a node type, which applies to a node or a group of nodes in a TreeView.
TreeNode Creates a node in a TreeView.

Reference documentation is provided for authoring with the TreeView ASP.NET controls and the TreeView behavior. For more information, see the TreeView Reference page.

The TreeView element is a container for TreeNode and TreeNodeType elements. Collectively, they define the structure, layout, and rendering of a tree view. A TreeView cannot contain any HTML content other than these three elements.

The TreeView element can contain an unlimited number of TreeNodeType elements, provided that sufficient resources are available on the client and host computers. TreeNodeType elements are used to define the styles, images, and other behaviors for TreeNode elements. TreeNode elements can be grouped by their Type, which allows them to be formatted and modified by using the TreeNodeType element. TreeNodeType elements must be children of the TreeView element and must occur before the first TreeNode element.

The TreeNode element can only contain other TreeNode elements. However, HTML content can be embedded into a TreeView by assigning it to the Text property of a TreeNode element. The Text content of a TreeNode element renders as HTML, rather than as plain text.

Writing a Simple TreeView

This section walks through the steps to create a simple TreeView. All the steps can be performed using any text editor.

In order to work through the following procedure, it is necessary to install the WebControls. For more information, see the Internet Explorer WebControls overview.

  1. Create a Web application.

    The Web should be named webcontrols, which will be used for all the samples in this article. The new Web must be configured as a Web application for the WebControls to run properly.

  2. Create an empty Web Forms page.

    Add a new file to the Web and save it as tree1.aspx.

  3. Add the import directive.

    Code the import directive for the WebControls on the first line of the Web Form. It should look like the following:

    <%@ import namespace="Microsoft.Web.UI.WebControls" %>
  4. Add the @ Register directive.

    Code the @ Register directive for the WebControls on the second line of the Web Form.

    <%@ Register TagPrefix="mytree" 
    Assembly="Microsoft.Web.UI.WebControls, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
  5. Add the document structure.

    Add the following content below the @ Register directive, to provide a basic document structure.

  6. Add a Form element.

    All WebControls elements must be authored inside a FORM element; therefore, add the following markup inside the document BODY.

    <FORM runat="server"></FORM>

    Note that the runat attribute is specified for the FORM, indicating that ASP.NET is to process the results of any user input.

    At this point the Web Form includes all the processing directives, elements, and content that are required to begin authoring with the WebControls elements. The contents of the tree1.aspx file should now look similar to the following:

    <%@ import namespace="Microsoft.Web.UI.WebControls" %>
    <%@ Register TagPrefix="mytree" 
    Assembly="Microsoft.Web.UI.WebControls, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
      <FORM runat="server"></FORM>

    Save the page and view it in your browser. If everything is correct, you should see only an empty page. The page is compiled before it is viewed, and any errors in the syntax will be raised. If you see an error at this point, correct the reported error. If the sample code provided above doesn't work, it is possible that the WebControls have probably not been installed correctly.

    Tip  For the adventurous reader: Try misspelling the value of the namespace or the assembly attributes in the declarations; save and view the page again. This is a useful exercise because you can see how the common language runtime reports errors for Web Forms.
  7. Add a TreeView element.

    Add a TreeView element as a child element of the FORM, and also set its runat attribute to server.

      <FORM runat="server">
      	<mytree:treeview runat="server"></mytree:treeview>

    At this point, the TreeView element doesn't contain any nodes, and so nothing renders in the Web page.

    Note  Notice the tag prefix for the TreeView element, the value mytree is used for all WebControls elements in the page because it has been predefined in the @ Register directive.
  8. Add a TreeNode to the TreeView.

    Next, add a TreeNode as a child element of the TreeView element.

    <mytree:treeview runat="server">
      <mytree:treenode text="My first Tree Node">

    The following image shows the initial rendering of the TreeView.

    TreeView Initial Rendering

    Since there is only one node, it is the root node and it has the focus. The coloring of the background is the default style, and this can be overridden by setting the appropriate properties. The node can be selected by clicking it.

  9. Add a second TreeNode.

    Add another TreeNode as a child element of the first TreeNode element.

    <mytree:treeview runat="server">
      <mytree:treenode text="My first Tree Node">
        <mytree:treenode text="My second Tree Node">
  10. Save and render the page.

    The following image shows a rendering of the initial state of the TreeView.

    TreeView Initial State

    Now the TreeView renders the root node, and it has a graphic that indicates it is expandable. The node can be expanded or collapsed by clicking on it.

    Note  This sample illustrates that the default state of a node in a TreeView is collapsed. The initial state of a node can be controlled by setting its Expanded property.

This concludes the basic TreeView sample. Further examples follow to illustrate additional properties and features of the TreeView.


This section discusses some useful techniques to customize the appearance of a TreeView UI. TreeNode elements can be formatted individually, and groups of nodes with the same Type can also be modified.

Frequently, it is desirable to render a unique graphic for each level of a TreeView. Sometimes it is necessary to customize the rendering for individual nodes, regardless of their depth in the tree and the style of their parent elements. The TreeView provides properties to cover all these possibilities.

Defining a TreeNodeType

The following sample renders a TreeView for a small collection of states and cities. As a first step toward customizing the appearance of the nodes, a TreeNodeType element has been used to define a Folder node Type.

<%@ import						
 namespace="Microsoft.Web.UI.WebControls" %> 
 <%@ Register TagPrefix="mytree" 
Assembly="Microsoft.Web.UI.WebControls, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<form id="myform" runat="server">
<mytree:treeview runat="server" ChildType="Folder">
<mytree:treenodetype Type="Folder"
   ImageUrl="./images/folder.gif" />
      <mytree:treenode Text="Michigan">
         <mytree:treenode Text="Detroit" />
         <mytree:treenode Text="Farmington" />
         <mytree:treenode Text="Southfield" />
      <mytree:treenode Text="Washington" >
         <mytree:treenode Text="Bellevue" />
         <mytree:treenode Text="Redmond" />
         <mytree:treenode Text="Woodinville" />

This sample illustrates the use of the TreeNodeType element, which is useful for formatting and structuring the layout and appearance of a TreeView. The ChildType attribute is specified as Folder on the TreeView element. Because the ChildType is specified on the TreeView, which is the container element for the entire tree, this has the effect of attributing all TreeNode elements with a Type equal to Folder. Clearly, this approach is far more efficient than it would be to add the Type attribute to each node.

Having declared the Folder ChildType on the TreeView, it is necessary to define this type using the TreeNodeType element. The TreeNodeType element in the sample, therefore, has the Type attribute set to the same value of Folder.

The ExpandedImageUrl and ImageUrl properties override the use of the default TreeView images for expanded and normal node rendering, respectively.

Customizing Tree Nodes by their Depth

In the next example, a few minor additions are made to the previous code, yielding customized folder icons for each level of the TreeView. In the following sample, two levels of TreeNode elements are used. In this case, nodes representing cities are nested inside nodes representing states.

<mytree:treeview runat="server" ChildType="Folder">
<mytree:treenodetype Type="Folder" ChildType="City" 
  ExpandedImageUrl="folderopen.gif" ImageUrl="folder.gif" />
<mytree:treenodetype Type="City" ImageUrl="html.gif" />
  <mytree:treenode Text="Michigan">
     <mytree:treenode Text="Detroit" />
     <mytree:treenode Text="Farmington" />
     <mytree:treenode Text="Southfield" />
  <mytree:treenode Text="Washington" >
     <mytree:treenode Text="Bellevue" />
     <mytree:treenode Text="Redmond" />
     <mytree:treenode Text="Woodinville" />

Notice that the ChildType attribute is used on the TreeView and the first TreeNodeType elements. The TreeView defines its children as having the Folder type and the first TreeNodeType element defines its children as having the City type. In this case, the second TreeNodeType element has no ChildType because this element defines the deepest TreeNodeType in the TreeView.

Applying Styles

The WebControls are rich controls, and when rendered in uplevel browsers, they support both mouse and keyboard operation. This means that based on a user's interaction, the elements of a TreeView UI may have different states. The WebControls provide special properties that simplify the customization of the appearance of elements based on their current state.

With each of these properties, one or more Cascading Style Sheets (CSS) attribute/value pairs can be defined. The format used is identical to the use of the standard CSS style attribute. Most commonly used styles that are used to apply fonts, colors and dimensions are supported, but not all CSS styles are supported by the WebControls.

<mytree:treenode Text="My Stylish Node" 
DefaultStyle="background:#CCCCCC;border:solid 1px;color:black;font-size:8pt"

Another possibility that can be used to format text is to apply HTML directly to the Text attribute.

<mytree:treenode Text="<i>Italicized Text</i> and <b>Bold Text</b>" />

Data Binding

The TreeView also supports data binding, which enables the generation of dynamic content. The following samples render TreeViews similar to the previous samples, but instead of using static content, XML files provide data source for the UI.

This example uses the TreeNodeSrc attribute to bind to the state_city.xml file, which populates the TreeView.

<mydbtree:treeview runat="server" SystemImagesPath="../images/" AutoPostBack="true">
  <mydbtree:treenode Text="North America" AutoPostBack=true imageurl="./images/root.gif" 
  Expanded="true" TreeNodeSrc="http://localhost/webcontrols/treeview/state_city.xml">

The code snippet shows how concise the markup in the .aspx file can be.

The state_city.xml file contains the following:

      <treenode Text="Michigan">
         <treenode Text="Detroit" />
         <treenode Text="Farmington" />
         <treenode Text="Southfield" />
      <treenode Text="Washington" >
         <treenode Text="Bellevue" />
         <treenode Text="Redmond" />
         <treenode Text="Woodinville" />

The next example shows how the TreeNodeTypeSrc attribute is used with XML. In the example, two XML files are used, one for the tree nodes and one for the node types. This builds on the first data binding example by adding additional customization to the UI.

Only a single TreeView element is used in the markup for the Web page, as shown by the following:

<mytree:treeview runat="server" SystemImagesPath="/webcontrols/images" AutoPostBack="true"

The content of the TreeNodeTypes.xml file looks like this.

	<TreeNodeType type="file" imageUrl="./images/html.gif" />
	<TreeNodeType type="folder" imageUrl="./images/folder.gif" />
	<TreeNodeType type="root" imageUrl="./images/root.gif" />

Data Binding with XML and XSL Templates

In certain scenarios, it may be necessary to use XML data that is read-only, and it may also be in a format that cannot be directly used to data bind to the TreeView. The TreeView also supports Extensible Stylesheet Language (XSL) templates, which can be used to transform an XML file into the correct format and structure. XSL can be used to XML files for data binding with both the TreeNode and TreeNodeType elements.

The following example shows how XML and XSL can be used to populate a TreeView.

Here is the markup for the TreeView element, which binds to an XML file, nodes.xml, and an XSL file, template.xsl.

  TreeNodeSrc = "nodes.xml"
  TreeNodeXsltSrc = "template.xsl"

The nodes.xml file contains the following:

<?xml version="1.0" ?>
   <HelpTOCNode Title="Web Sites">
      <HelpTOCNode Title = "Microsoft" Url = "http://www.microsoft.com">
      <HelpTOCNode Title = "MSDN" Url = "http://msdn.microsoft.com">

The template.xsl file contains the following:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version='1.0'>
  <xsl:template match="/">
       <xsl:for-each select="HelpTOC/HelpTOCNode">
          <xsl:element name="TreeNode">
             <xsl:attribute name="Text" ><xsl:value-of select="@Title"/></xsl:attribute>
             <xsl:attribute name="NavigateURL" ><xsl:value-of select="@Url"/></xsl:attribute>
             <xsl:attribute name="TARGET" >main</xsl:attribute>

               <xsl:for-each select="HelpTOCNode">

                  <xsl:element name="TreeNode">
                     <xsl:attribute name="Text" ><xsl:value-of select="@Title"/></xsl:attribute>
                     <xsl:attribute name="NavigateURL" ><xsl:value-of select="@Url"/></xsl:attribute>
                     <xsl:attribute name="Target" >main</xsl:attribute>


The XSL transforms the source XML into the correct format for the TreeView.

Warning  The TREENODES and TREENODETYPES elements in a data binding source document must be uppercase for the TreeView data binding to work.

Data Binding to Multiple XML Files

If the XML data for your TreeView is divided into several files, it is still possible to data bind to multiple sources. For example, individual TreeNode elements can bind to separate XML and XSL files.

It is also possible to specify the TreeNodeTypeSrc, TreeNodeSrc, and TreeNodeXsltSrc attributes in a databound XML file. If XML data includes attributes that point to other XML files, this can be transformed to the appropriate TreeView markup using XSL.

When building a TreeView with multiple XML files, all of the databound nodes of the tree are not loaded at once. When the TreeNodeSrc property is set for a TreeNode element, the contents of the node aren't actually bound to the XML source until the node is expanded.

When binding the TreeView element to a data source, it fetches the XML source data for all of its root nodes. If those root nodes also have TreeNodeSrc attributes, those attributes are ignored until the user expands a root node. At that point, the expanded node is bound to its data source, and its children are downloaded and rendered. It is possible, therefore, to dynamically bind a node's children to an XML source if, when the parent generates the XML for its children, the XML contains the TreeNodeSrc used by the child element to data bind.

A node's TreeNodeSrc property is ignored until the node is first expanded. The TreeNodeSrc attribute can be modified dynamically before a node is expanded. When the node is expanded for the first time, it binds to whatever XML data its current TreeNodeSrc points to.

Data Binding with XML and SQL Server

Other providers of XML data can also be used with the WebControls elements, as illustrated by the following:

<ie:treenode Text="root" type="tree" Expanded="true"
 TreeNodeSrc="http://localhost/mySQLXML?sql=execute+sp_GenMyXML+@pid=1" />

This example uses a more advanced technique. The TreeNodeSrc attribute is set to a URL that runs a stored procedure on a Microsoft SQL Server database, which generates the XML data island dynamically.

The examples provided illustrate how simple it can be to take advantage of data binding with the TreeView.

Namespace Inheritance in Data Binding

When data binding WebControls elements to XML data islands, the XML content used to populate the controls must not use a namespace prefix. This is because the namespace is implied by the element that acts as the data consumer. For a more detailed explanation, see the TreeNodeTypeSrc and TreeNodeSrc.


The samples presented so far show that in most cases no programming is required to write a fully functional UI element. This section provides a brief introduction to some simple scripting techniques that can be used with the TreeView.

TreeView Events

Events arising from user interaction can be directed to the server by setting the AutoPostBack property to true. Server-side script should be used when handling events for both uplevel and downlevel browsers because the rich DHTML behaviors used in the Internet Explorer 5.5 or later versions are not used in the downlevel page content.

For a Web page that has a TreeView, the main interaction by the user is to expand and collapse the nodes in the tree to explore the content. The following sample code shows how the onexpand, oncollapse, and onselectedindexchange events can be handled in a Web Form using C#.

<script language="C#" runat="server">
void myExpandFn(object sender, TreeViewClickEventArgs e)
  mylabel.InnerText += "Expanded (Node Index= " + e.Node.ToString() + ")";

void myCollapseFn(object sender, TreeViewClickEventArgs e)
  mylabel.InnerText += "Collapsed (Node Index = " + e.Node.ToString() + ")";

void mySelectChangeFn(Object sender, TreeViewSelectEventArgs e)
  mylabel.InnerText += "Selected " + e.NewNode.ToString() + " (old Node
  Index=" + e.OldNode.ToString()+")" ;

In this script, the presence of an element with an id of mylabel is required.

<div id=mylabel runat="server">Event Log: </div>
Note  This tag must also be placed inside the FORM element used by the TreeView.

The functions in the C# script can be attached to events programmatically or by using attributes on the TreeView, as shown by the following:


The onexpand and oncollapse events are frequently used when programming with the TreeView. In this example, the script appends to the innerText of the div element each time a node is expanded or collapsed.

Server-side Includes

Because the WebControls are authored with ASP.NET, server-side includes are also supported. The following examples show how this can be accomplished.

<mytree:treeview runat="server">
    <!-- #Include file="nodes.txt" -->

The nodes.txt file is used to populate a TreeView, and in the following example, included files are used to populate two separate TreeNode branches of a TreeView.

<mytree:treeview runat="server">
    <mytree:treenode Text="Books" >
        <!-- #Include file="Books.txt" -->
    <mytree:treenode Text="Magazines" >
        <!-- #Include file="magazines.txt" -->

Unlike the namespace-prefixing rules that apply to data binding with XML, the content of an included file must have elements that use the same tag prefix as the parent elements. Therefore, the contents of the books.txt and magazines.txt files would use the mytree tag prefix.

Performance Tips

This section provides practical recommendations for using the TreeView.

Tree Size

Rendering enormous hierarchical data sets in a single TreeView data island is not recommended. As a general rule, try to keep the number of nodes in a tree under 1000.

Each time an update is made to the UI of a TreeView control, for example, whenever a node is expanded or collapsed, additional data is appended to the view state, which maintains a history of state changes in the Web page. This means that each time a view is updated with a large data island, the amount of data appended to the view state history is increased. In ASP.NET, there is a limit in the size of the view state, so the combination of very large tree hierarchies combined with multiple updates may cause performance problems, and in certain cases portions of the history could be lost.

Related Topics