Export (0) Print
Expand All

TreeView Class

Note: This class is new in the .NET Framework version 2.0.

Displays hierarchical data, such as a table of contents, in a tree structure.

Namespace: System.Web.UI.WebControls
Assembly: System.Web (in system.web.dll)

[ControlValuePropertyAttribute("SelectedValue")] 
public class TreeView : HierarchicalDataBoundControl, IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler
/** @attribute ControlValuePropertyAttribute("SelectedValue") */ 
public class TreeView extends HierarchicalDataBoundControl implements IPostBackEventHandler, IPostBackDataHandler, 
	ICallbackEventHandler
ControlValuePropertyAttribute("SelectedValue") 
public class TreeView extends HierarchicalDataBoundControl implements IPostBackEventHandler, IPostBackDataHandler, 
	ICallbackEventHandler

The TreeView control is used to display hierarchical data, such as a table of contents or file directory, in a tree structure and supports the following features:

  • Data binding that allows the nodes of the control to be bound to XML, tabular, or relational data.

  • Site navigation through integration with the SiteMapDataSource control.

  • Node text that can be displayed as either plain text or hyperlinks.

  • Programmatic access to the TreeView object model to create trees, populate nodes, set properties, and so on dynamically.

  • Client-side node population (on supported browsers).

  • The ability to display a check box next to each node.

  • Customizable appearance through themes, user-defined images, and styles.

Nodes

The TreeView control is made up of nodes. Each entry in the tree is called a node and is represented by a TreeNode object. Node types are defined as follows:

  • A node that contains other nodes is called a parent node.

  • The node that is contained by another node is called a child node.

  • A node that has no children is called a leaf node.

  • The node that is not contained by any other node but is the ancestor to all the other nodes is the root node.

A node can be both a parent and a child, but root, parent, and leaf nodes are mutually exclusive. Several visual and behavioral properties of nodes are determined by whether a node is a root, parent, or leaf node.

Although a typical tree structure has only one root node, the TreeView control allows you to add multiple root nodes to your tree structure. This is useful when you want to display item listings without displaying a single root node, as in a list of product categories.

Each node has a Text property and a Value property. The value of the Text property is displayed in the TreeView, while the Value property is used to store any additional data about the node, such as data that is passed to the postback event that is associated with the node.

A node can be in one of two modes: selection mode and navigation mode. By default, a node is in selection mode. To put a node into navigation mode, set the NavigateUrl property for the node to a value other than an empty string (""). To put a node into selection mode, set the NavigateUrl property for the node to an empty string ("").

Static Data

The simplest data model of the TreeView control is static data. To display static data using declarative syntax, first nest opening and closing <Nodes> tags between the opening and closing tags of the TreeView control. Next, create the tree structure by nesting <asp:TreeNode> elements between the opening and closing <Nodes> tags. Each <asp:TreeNode> element represents a node in the tree and maps to a TreeNode object. You can set the properties of each node by setting the attributes of its <asp:TreeNode> element. To create child nodes, nest additional <asp:TreeNode> elements between the opening and closing <asp:TreeNode> tags of the parent node.

Binding to Data

The TreeView control can also be bound to data. You can use either of two methods to bind the TreeView control to the appropriate data source type:

  • The TreeView control can use any data source control that implements the IHierarchicalDataSource interface, such as an XmlDataSource control or a SiteMapDataSource control. To bind to a data source control, set the DataSourceID property of the TreeView control to the ID value of the data source control. The TreeView control automatically binds to the specified data source control. This is the preferred method to bind to data.

  • The TreeView control can also be bound to an XmlDocument object or a DataSet object with relations. To bind to one of these data sources, set the DataSource property of the TreeView control to the data source, and then call the DataBind method.

When binding to a data source where each data item contains multiple properties (such as an XML element with several attributes), a node displays the value that is returned by the ToString method of the data item, by default. In the case of an XML element, the node displays the element name, which shows the underlying structure of the tree but is not very useful otherwise. You can bind a node to a specific data item property by specifying tree node bindings using the DataBindings collection. The DataBindings collection contains TreeNodeBinding objects that define the relationship between a data item and the node that it is binding to. You can specify the criteria for binding and the data item property to display in the node. For more information on tree node bindings, see TreeNodeBinding.

Security noteSecurity Note

A malicious user can create a callback request and get data for the nodes of the TreeView control that the page developer is not displaying. Therefore, security of the data must be implemented by the data source. Do not use the MaxDataBindDepth property to hide data.

Dynamic Node Population

Sometimes, it is not practical to statically define the tree structure because the data source returns too much data or because the data to display depends on information that you get at run time. Because of this, the TreeView control supports dynamic node population. When the PopulateOnDemand property for a node is set to true, that node gets populated at run time when the node is expanded. To populate a node dynamically, you must define an event-handling method that contains the logic to populate a node for the TreeNodePopulate event.

Microsoft Internet Explorer version 5.0 and later and Netscape 6.0 and later can also take advantage of client-side node population. Client-side node population enables the TreeView control to populate a node using client script when users expand the node, without requiring a round trip to the server. For more information on client-side node population, see PopulateNodesFromClient.

Customizing the User Interface

There are many ways to customize the appearance of the TreeView control. First, you can specify a different style (such as font size and color) for each of the node types. The following table lists the available node styles.

Node style property

Description

HoverNodeStyle

The style settings for a node when the mouse pointer is positioned over it.

LeafNodeStyle

The style settings for the leaf nodes.

NodeStyle

The default style settings for a node.

ParentNodeStyle

The style settings for the parent nodes.

RootNodeStyle

The style settings for the root node.

SelectedNodeStyle

The style settings for a selected node.

You can also control the style of nodes at specific depths within the tree by using the LevelStyles collection. The first style in the collection corresponds to the style of the nodes at the first level in the tree. The second style in the collection corresponds to the style of the nodes at the second level in the tree, and so on. This is most often used to generate table of contents–style navigation menus where nodes at a certain depth should have the same appearance, regardless of whether they have child nodes.

NoteNote

If a style is defined for a certain depth level using the LevelStyles collection, that style overrides any root, parent, or leaf node style settings for the nodes at that depth.

Another way to alter the appearance of the control is to customize the images that are displayed in the TreeView control. You can specify your own custom set of images for the different parts of the control by setting the properties shown in the following table.

Image property

Description

CollapseImageUrl

The URL to an image displayed for the collapsible node indicator. This image is usually a minus sign (-).

ExpandImageUrl

The URL to an image displayed for the expandable node indicator. This image is usually a plus sign (+).

LineImagesFolder

The URL to the folder containing the line images used to connect parent nodes to child nodes. The ShowLines property must also be set to true for this property to have an effect.

NoExpandImageUrl

The URL to an image displayed for the non-expandable node indicator.

NoteNote

You do not need to customize every image property. If an image property is not explicitly set, the built-in default image is used.

The TreeView control also allows you to display a check box next to a node. When the ShowCheckBoxes property is set to a value other than TreeNodeTypes.None, check boxes are displayed next to the specified node types.

NoteNote

The ShowCheckBoxes property can be set to a bitwise combination of the TreeNodeTypes enumeration member values.

Each time the page is posted to the server, the CheckedNodes collection is automatically populated with the selected nodes. When check boxes are displayed, you can use the TreeNodeCheckChanged event to run a custom routine whenever the state of a check box changes between posts to the server.

Events

The TreeView control provides several events that you can program against. This allows you to run a custom routine whenever an event occurs. The following table lists the events that are supported by the TreeView control.

Event

Description

TreeNodeCheckChanged

Occurs when the check boxes of the TreeView control change state between posts to the server.

SelectedNodeChanged

Occurs when a node is selected in the TreeView control.

TreeNodeExpanded

Occurs when a node is expanded in the TreeView control.

TreeNodeCollapsed

Occurs when a node is collapsed in the TreeView control.

TreeNodePopulate

Occurs when a node with its PopulateOnDemand property set to true is expanded in the TreeView control.

TreeNodeDataBound

Occurs when a data item is bound to a node in the TreeView control.

Accessibility

The markup rendered by default for this control might not conform to accessibility standards such as the Web Content Accessibility Guidelines 1.0 (WCAG) priority 1 guidelines. For details about accessibility support for this control, see ASP.NET Controls and Accessibility.

Scrolling

The TreeView control does not have built-in scrolling. To add scrolling, place the TreeView control in a Panel control and add scrollbars to the Panel control. For more information, see Panel Web Server Control Overview.

TopicLocation
How to: Programmatically Enumerate Site-Map NodesBuilding ASP .NET Web Applications
How to: Configure Multiple Site Maps and Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server ControlsBuilding ASP .NET Web Applications
How to: Customize the Appearance of SiteMapPath Web Server ControlsBuilding ASP .NET Web Applications
How to: Display Site-Map Data in Non-Hierarchical Web Server ControlsBuilding ASP .NET Web Applications
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications
How to: Implement ASP.NET Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Programmatically Enumerate Site-Map NodesBuilding ASP .NET Web Applications
How to: Configure Multiple Site Maps and Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server ControlsBuilding ASP .NET Web Applications
How to: Customize the Appearance of SiteMapPath Web Server ControlsBuilding ASP .NET Web Applications
How to: Display Site-Map Data in Non-Hierarchical Web Server ControlsBuilding ASP .NET Web Applications
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications
How to: Implement ASP.NET Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Add or Delete TreeView Node Elements (Visual Studio)Building ASP .NET Web Applications in Visual Studio
Walkthrough: Displaying Hierarchical Data in a TreeView ControlBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Adding Site Navigation to a Web SiteBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Filtering Site-Map Nodes Based on Security RolesBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Customizing a Web Site Using Themes in Visual StudioBuilding ASP .NET Web Applications in Visual Studio
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications in Visual Studio

This section contains seven code examples:

  • The first code example demonstrates how to set up the frames for the second code example.

  • The second code example demonstrates how to use declarative syntax to display static data in the TreeView control.

  • The third code example demonstrates how to bind the TreeView control to an XML data source.

  • The fourth code example provides sample XML data for the third code example.

  • The fifth code example demonstrates how to use the TreeView control for site navigation by binding it to a SiteMapDataSource control.

  • The sixth code example provides sample site map data for the fifth code example.

  • The seventh code example demonstrates how to populate the nodes in the TreeView control from the client.

The following code example demonstrates how to set up the frames for the following code example.


<html>
         
    <frameset cols="30%, 75%">
   
        <frame name="Menu" src="TreeViewFramecs.aspx"/>
        <frame name="Content" src="Home.aspx"/> 
           
    </frameset>      
   
</html>


The following code example demonstrates how to use declarative syntax to display static data in the TreeView control. This example is used within the frame set of the preceding example to display a table of contents.


<%@ Page Language="C#" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView Declarative Syntax Example</h3>
      
      <asp:TreeView id="SampleTreeView" 
        runat="server">
         
        <Nodes>
        
          <asp:TreeNode Value="Home" 
            NavigateUrl="Home.aspx" 
            Text="Home"
            Target="Content" 
            Expanded="True">
             
            <asp:TreeNode Value="Page 1" 
              NavigateUrl="Page1.aspx" 
              Text="Page1"
              Target="Content">
               
              <asp:TreeNode Value="Section 1" 
                NavigateUrl="Section1.aspx" 
                Text="Section 1"
                Target="Content"/>
                 
            </asp:TreeNode>              
            
            <asp:TreeNode Value="Page 2" 
              NavigateUrl="Page2.aspx"
              Text="Page 2"
              Target="Content">
               
            </asp:TreeNode> 
            
          </asp:TreeNode>
        
        </Nodes>
        
      </asp:TreeView>

    </form>
  </body>
</html>


The following code example demonstrates how to bind the TreeView control to an XML data source. For this example to work correctly, you must copy the sample XML data, provided after this code example, to a file named Book.xml.


<%@ Page Language="C#" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView XML Data Binding Example</h3>
    
      <asp:TreeView id="BookTreeView" 
        DataSourceID=BookXmlDataSource
        runat="server">
         
        <DataBindings>
          <asp:TreeNodeBinding DataMember="Book" TextField="Title"/>
          <asp:TreeNodeBinding DataMember="Chapter" TextField="Heading"/>
          <asp:TreeNodeBinding DataMember="Section" TextField="Heading"/>
        </DataBindings>
         
      </asp:TreeView>

      <asp:XmlDataSource id="BookXmlDataSource"  
        DataFile="Book.xml"
        runat="server">
      </asp:XmlDataSource>
    
    </form>
  </body>
</html>


The following code example provides sample XML data for the preceding example.

<Book Title="Book Title">
    <Chapter Heading="Chapter 1">
        <Section Heading="Section 1">
        </Section>
        <Section Heading="Section 2">
        </Section>
    </Chapter>
    <Chapter Heading="Chapter 2">
        <Section Heading="Section 1">
        </Section>
    </Chapter>
</Book>

The following code example demonstrates how to use the TreeView control for site navigation by binding it to a SiteMapDataSource control. For this example to work correctly, you must copy the sample site map data, provided after this code example, to a file named Web.sitemap.


<%@ Page Language="C#" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView AutoGenerateBindings Example</h3>
    
      <!-- Set the AutoGenerateBindings property -->
      <!-- to false declaratively to allow for   -->
      <!-- the user-defined Bindings collection. -->
      <asp:TreeView id="SiteTreeView" 
        DataSourceID="SiteMapSource"
        AutoGenerateDataBindings="False"
        runat="server">
        
        <DataBindings>
        
          <asp:TreeNodeBinding TextField="title" NavigateUrlField="url"/>
        
        </DataBindings>
            
      </asp:TreeView>
      
      <asp:SiteMapDataSource ID="SiteMapSource" runat="server"/>
         
    </form>
  </body>
</html>


The following code example provides sample site map data for the preceding code example.

<siteMap>
    <siteMapNode title="Home" description="Home" url="default.aspx">
        <siteMapNode title="Products" description="Products" url="Products.aspx">
            <siteMapNode title="Computers" url="Computers.aspx"/>
            <siteMapNode title="Accessories" url="Accessories.aspx"/>     
        </siteMapNode>
    </siteMapNode>
</siteMap>

The following code example demonstrates how to populate the nodes in the TreeView control from the client. When client-side node population is enabled, nodes are populated dynamically on the client, without the need to post back to the server.


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">

  void PopulateNode(Object sender, TreeNodeEventArgs e)
  {

    // Call the appropriate method to populate a node at a particular level.
    switch(e.Node.Depth)
    {
      case 0:
        // Populate the first-level nodes.
        PopulateCategories(e.Node);
        break;
      case 1:
        // Populate the second-level nodes.
        PopulateProducts(e.Node);
        break;
      default:
        // Do nothing.
        break;
    }
    
  }

  void PopulateCategories(TreeNode node)
  {
    
    // Query for the product categories. These are the values
    // for the second-level nodes.
    DataSet ResultSet = RunQuery("Select CategoryID, CategoryName From Categories");

    // Create the second-level nodes.
    if(ResultSet.Tables.Count > 0)
    {
    
      // Iterate through and create a new node for each row in the query results.
      // Notice that the query results are stored in the table of the DataSet.
      foreach (DataRow row in ResultSet.Tables[0].Rows)
      {
        
        // Create the new node. Notice that the CategoryId is stored in the Value property 
        // of the node. This will make querying for items in a specific category easier when
        // the third-level nodes are created. 
        TreeNode newNode = new TreeNode();
        newNode.Text = row["CategoryName"].ToString(); 
        newNode.Value = row["CategoryID"].ToString();        

        // Set the PopulateOnDemand property to true so that the child nodes can be 
        // dynamically populated.
        newNode.PopulateOnDemand = true;
        
        // Set additional properties for the node.
        newNode.SelectAction = TreeNodeSelectAction.Expand;
        
        // Add the new node to the ChildNodes collection of the parent node.
        node.ChildNodes.Add(newNode);
        
      }
      
    }
    
  }

  void PopulateProducts(TreeNode node)
  {

    // Query for the products of the current category. These are the values
    // for the third-level nodes.
    DataSet ResultSet = RunQuery("Select ProductName From Products Where CategoryID=" + node.Value);

    // Create the third-level nodes.
    if(ResultSet.Tables.Count > 0)
    {
    
      // Iterate through and create a new node for each row in the query results.
      // Notice that the query results are stored in the table of the DataSet.
      foreach (DataRow row in ResultSet.Tables[0].Rows)
      {
      
        // Create the new node.
        TreeNode NewNode = new TreeNode(row["ProductName"].ToString());
        
        // Set the PopulateOnDemand property to false, because these are leaf nodes and
        // do not need to be populated.
        NewNode.PopulateOnDemand = false;
        
        // Set additional properties for the node.
        NewNode.SelectAction = TreeNodeSelectAction.None;
        
        // Add the new node to the ChildNodes collection of the parent node.
        node.ChildNodes.Add(NewNode);
        
      }
      
    }

  }

  DataSet RunQuery(String QueryString)
  {

    // Declare the connection string. This example uses Microsoft SQL Server 
    // and connects to the Northwind sample database.
    String ConnectionString = "server=localhost;database=NorthWind;Integrated Security=SSPI"; 

    SqlConnection DBConnection = new SqlConnection(ConnectionString);
    SqlDataAdapter DBAdapter;
    DataSet ResultsDataSet = new DataSet();

    try
    {

      // Run the query and create a DataSet.
      DBAdapter = new SqlDataAdapter(QueryString, DBConnection);
      DBAdapter.Fill(ResultsDataSet);

      // Close the database connection.
      DBConnection.Close();

    }
    catch(Exception ex)
    {

      // Close the database connection if it is still open.
      if(DBConnection.State == ConnectionState.Open)
      {
        DBConnection.Close();
      }
      
      Message.Text = "Unable to connect to the database.";

    }

    return ResultsDataSet;

  }

</script>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView PopulateNodesFromClient Example</h3>
    
      <asp:TreeView id="LinksTreeView"
        Font-Name= "Arial"
        ForeColor="Blue"
        EnableClientScript="true"
        PopulateNodesFromClient="true"  
        OnTreeNodePopulate="PopulateNode"
        runat="server">
         
        <Nodes>
        
          <asp:TreeNode Text="Inventory" 
            SelectAction="Expand"  
            PopulateOnDemand="true"/>
        
        </Nodes>
        
      </asp:TreeView>
      
      <br><br>
      
      <asp:Label id="Message" runat="server"/>

    </form>
  </body>
</html>


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft