System.Web.UI.WebControls


.NET Framework 类库
TreeView 类

注意:此类在 .NET Framework 2.0 版中是新增的。

在树结构中显示分层数据,例如目录。

命名空间:System.Web.UI.WebControls
程序集:System.Web(在 system.web.dll 中)

语法

Visual Basic(声明)
<ControlValuePropertyAttribute("SelectedValue")> _
Public Class TreeView
    Inherits HierarchicalDataBoundControl
    Implements IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler
Visual Basic(用法)
Dim instance As TreeView
C#
[ControlValuePropertyAttribute("SelectedValue")] 
public class TreeView : HierarchicalDataBoundControl, IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler
C++
[ControlValuePropertyAttribute(L"SelectedValue")] 
public ref class TreeView : public HierarchicalDataBoundControl, IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler
J#
/** @attribute ControlValuePropertyAttribute("SelectedValue") */ 
public class TreeView extends HierarchicalDataBoundControl implements IPostBackEventHandler, IPostBackDataHandler, 
    ICallbackEventHandler
JScript
ControlValuePropertyAttribute("SelectedValue") 
public class TreeView extends HierarchicalDataBoundControl implements IPostBackEventHandler, IPostBackDataHandler, 
    ICallbackEventHandler
备注

TreeView 控件用于在树结构中显示分层数据,例如目录或文件目录,并且支持下列功能:

  • 数据绑定,它允许控件的节点绑定到 XML、表格或关系数据。

  • 站点导航,通过与 SiteMapDataSource 控件集成实现。

  • 节点文本既可以显示为纯文本也可以显示为超链接。

  • 借助编程方式访问 TreeView 对象模型以动态地创建树、填充节点、设置属性等。

  • 客户端节点填充(在支持的浏览器上)。

  • 在每个节点旁显示复选框的功能。

  • 通过主题、用户定义的图像和样式可实现自定义外观。

节点

TreeView 控件由节点组成。树中的每个项都称为一个节点,它由一个 TreeNode 对象表示。节点类型的定义如下:

  • 包含其他节点的节点称为“父节点”。

  • 被其他节点包含的节点称为“子节点”。

  • 没有子节点的节点称为“叶节点”。

  • 不被其他任何节点包含同时是所有其他节点的上级的节点是“根节点”。

一个节点可以同时是父节点和子节点,但是不能同时为根节点、父节点和叶节点。节点为根节点、父节点还是叶节点决定着节点的几种可视化属性和行为属性。

尽管通常的树结构只具有一个根节点,但是 TreeView 控件允许您向树结构中添加多个根节点。如果要在不显示单个根节点的情况下显示项列表(如同在产品类别列表中),这种控件就非常有用。

每个节点具有一个 Text 属性和一个 Value 属性。Text 属性的值显示在 TreeView 中,而 Value 属性用于存储有关节点的任何其他数据,例如传递到与该节点相关联的回发事件的数据。

节点可以处于以下两种状态之一:选定状态和导航状态。默认情况下,会有一个节点处于选定状态。若要使一个节点处于导航状态,请将该节点的 NavigateUrl 属性值设置为空字符串 ("") 以外的值。若要使一个节点处于选定状态,请将该节点的 NavigateUrl 属性值设置为空字符串 ("")。

静态数据

TreeView 控件的最简单的数据模型是静态数据。若要使用声明性语法显示静态数据,首先在 TreeView 控件的开始标记和结束标记之间嵌套开始和结束 <Nodes> 标记。然后,通过在开始和结束 <Nodes> 标记之间嵌套 <asp:TreeNode> 元素来创建树结构。每个 <asp:TreeNode> 元素表示树中的一个节点,并且映射到一个 TreeNode 对象。通过设置每个节点的 <asp:TreeNode> 元素的属性 (Attribute),可以设置该节点的属性 (Property)。若要创建子节点,请在父节点的开始和结束 <asp:TreeNode> 标记之间嵌套其他的 <asp:TreeNode> 元素。

绑定到数据

TreeView 控件还可以绑定到数据。您可以使用以下两种方法中的任意一种将 TreeView 控件绑定到适当的数据源类型:

  • TreeView 控件可以使用实现 IHierarchicalDataSource 接口的任意数据源控件,例如 XmlDataSource 控件或 SiteMapDataSource 控件。若要绑定到数据源控件,请将 TreeView 控件的 DataSourceID 属性设置为数据源控件的 ID 值。TreeView 控件自动绑定到指定的数据源控件。这是绑定到数据的首选方法。

  • TreeView 控件还可以绑定到 XmlDocument 对象或包含关系的 DataSet 对象。若要绑定到这些数据源中的一个,请将 TreeView 控件的 DataSource 属性设置为该数据源,然后调用 DataBind 方法。

如果数据源中的每个数据项包含多个属性 (Property)(例如包含多个属性 (Attribute) 的 XML 元素),在绑定到该数据源时,默认情况下节点会显示由数据项的 ToString 方法返回的值。如果遇到 XML 元素,则节点会显示该元素的名称,这样将显示该树的基础结构,但除此之外没有什么用处。通过使用 DataBindings 集合指定树节点绑定,可以将节点绑定到特定数据项属性。DataBindings 集合包含 TreeNodeBinding 对象,这些对象定义数据项与其绑定到的节点之间的关系。您可以指定要在节点中显示的绑定条件和数据项属性。有关树节点绑定的更多信息,请参见 TreeNodeBinding

Security note安全注意

恶意用户可以创建回调请求并获取页面开发人员没有显示的 TreeView 控件的节点数据。因此,必须由数据源实现数据的安全性。请不要用 MaxDataBindDepth 属性来隐藏数据。

动态节点填充

有时,静态地定义树结构并不可行,因为数据源可能返回太多数据或者要显示的数据取决于在运行时您所获取的信息。因此,TreeView 控件支持动态节点填充。如果将某节点的 PopulateOnDemand 属性设置为 true,则展开该节点后在运行时填充该节点。若要动态填充某节点,您必须定义一个事件处理方法,它包含 TreeNodePopulate 事件所用的填充节点的逻辑。

Microsoft Internet Explorer 版本 5.0 和更高版本以及 Netscape 6.0 和更高版本还可以利用客户端节点填充。利用客户端节点填充,TreeView 控件可以在用户展开节点时使用客户端脚本填充节点,无需访问服务器。有关客户端节点填充的更多信息,请参见 PopulateNodesFromClient

自定义用户界面

自定义 TreeView 控件的外观有很多方法。首先,可以为每个节点类型指定不同的样式(例如字号和颜色)。下表列出了可用的节点样式。

节点样式属性

说明

HoverNodeStyle

鼠标指针停在节点上时,该节点的样式设置。

LeafNodeStyle

叶节点的样式设置。

NodeStyle

节点的默认样式设置。

ParentNodeStyle

父节点的样式设置。

RootNodeStyle

根节点的样式设置。

SelectedNodeStyle

选定节点的样式设置。

还可以使用 LevelStyles 集合控制树中特定深度的节点样式。集合中的第一种样式对应于树中第一级节点的样式。集合中的第二种样式对应于树中第二级节点的样式,依此类推。此集合最常用于生成目录样式的导航菜单;在这种导航菜单中,某一深度的节点不管是否具有子节点,都会有相同的外观。

Note注意

如果使用 LevelStyles 集合为某个深度级别定义了样式,则该样式会重写该深度的节点的所有根节点、父节点或叶节点的样式设置。

改变控件外观的另一种方法是自定义显示在 TreeView 控件中的图像。通过设置下表中显示的属性,您可以为控件的不同部分指定您自己的自定义图像集。

图像属性

说明

CollapseImageUrl

可折叠节点的指示符所显示图像的 URL。此图像通常为一个减号 (-)。

ExpandImageUrl

可展开节点的指示符所显示图像的 URL。此图像通常为一个加号 (+)。

LineImagesFolder

包含用于连接父节点和子节点的线条图像的文件夹的 URL。ShowLines 属性还必须设置为 true,该属性才能有效。

NoExpandImageUrl

不可展开节点的指示符所显示图像的 URL。

Note注意

不需要自定义每个图像属性。如果没有显式设置图像属性,则使用内置的默认图像。

TreeView 控件还允许您在节点旁显示一个复选框。在将 ShowCheckBoxes 属性设置为 TreeNodeTypes.None 以外的值时,会在指定类型的节点旁显示复选框。

Note注意

ShowCheckBoxes 属性可以设置为 TreeNodeTypes 枚举成员值的按位组合。

每次将页面发送到服务器时,选定的节点会自动填充到 CheckedNodes 集合中。如果显示了复选框,每当复选框状态在两次向服务器发送之间更改时,可以使用 TreeNodeCheckChanged 事件运行自定义例程。

事件

TreeView 控件提供多个您可以对其进行编程的事件。这使您可以在每次发生事件时运行一个自定义例程。下表列出了 TreeView 控件支持的事件。

事件

说明

TreeNodeCheckChanged

TreeView 控件的复选框在向服务器的两次发送过程之间状态有所更改时发生。

SelectedNodeChanged

当选择 TreeView 控件中的节点时发生。

TreeNodeExpanded

当扩展 TreeView 控件中的节点时发生。

TreeNodeCollapsed

当折叠 TreeView 控件中的节点时发生。

TreeNodePopulate

当其 PopulateOnDemand 属性设置为 true 的节点在 TreeView 控件中展开时发生。

TreeNodeDataBound

当数据项绑定到 TreeView 控件中的节点时发生。

辅助功能

默认情况下,为此控件呈现的标记可能不符合辅助功能标准,例如 Web 内容辅助功能准则 1.0 (WCAG) 优先级 1 准则。有关此控件的辅助功能支持的详细信息,请参见 ASP.NET 控件和辅助功能

滚动

TreeView 控件没有内置的滚动。若要添加滚动,请将 TreeView 控件放置在 Panel 控件中,并将滚动条添加到 Panel 控件。有关更多信息,请参见 Panel Web 服务器控件概述

TopicLocation
如何:以编程方式枚举站点地图节点生成 ASP .NET Web 应用程序
如何:以编程方式枚举站点地图节点在 Visual Studio 中生成 ASP .NET Web 应用程序
如何:在不分层的 Web 服务器控件中显示站点地图数据生成 ASP .NET Web 应用程序
如何:在非分层 Web 服务器控件中显示站点地图数据在 Visual Studio 中生成 ASP .NET Web 应用程序
如何:实现 ASP.NET 站点地图提供程序生成 ASP .NET Web 应用程序
如何:实现 ASP.NET 站点地图提供程序在 Visual Studio 中生成 ASP .NET Web 应用程序
如何:添加或删除 TreeView 节点元素在 Visual Studio 中生成 ASP .NET Web 应用程序
如何:添加或删除 TreeView 节点元素 (Visual Studio)在 Visual Studio 中构建 ASP .NET Web 应用程序
如何:添加简单的站点导航生成 ASP .NET Web 应用程序
如何:添加简单的站点导航在 Visual Studio 中生成 ASP .NET Web 应用程序
如何:筛选 SiteMapDataSource Web 服务器控件检索到的节点生成 ASP .NET Web 应用程序
如何:筛选 SiteMapDataSource Web 服务器控件检索到的节点在 Visual Studio 中生成 ASP .NET Web 应用程序
如何:自定义 SiteMapPath Web 服务器控件的外观生成 ASP .NET Web 应用程序
如何:自定义 SiteMapPath Web 服务器控件的外观在 Visual Studio 中生成 ASP .NET Web 应用程序
如何:配置多个站点地图和站点地图提供程序生成 ASP .NET Web 应用程序
如何:配置多个站点地图和站点地图提供程序在 Visual Studio 中生成 ASP .NET Web 应用程序
演练:使用主题自定义网站在 Visual Studio 中构建 ASP .NET Web 应用程序
演练:使用主题自定义网站使用 Visual Web Developer 生成应用程序
演练:向网站添加站点导航在 Visual Studio 中构建 ASP .NET Web 应用程序
演练:向网站添加站点导航使用 Visual Web Developer 生成应用程序
演练:在 TreeView 控件中显示分层数据在 Visual Studio 中构建 ASP .NET Web 应用程序
演练:在 TreeView 控件中显示分层数据在 Visual Studio 中生成 ASP .NET Web 应用程序
演练:根据安全角色筛选站点地图节点在 Visual Studio 中构建 ASP .NET Web 应用程序
演练:根据安全角色筛选站点地图节点在 Visual Studio 中生成 ASP .NET Web 应用程序
示例

本节包含七个代码示例:

  • 第一个代码示例演示如何为第二个代码示例设置框架。

  • 第二个代码示例演示如何使用声明性语法在 TreeView 控件中显示静态数据。

  • 第三个代码示例演示如何将 TreeView 控件绑定到 XML 数据源。

  • 第四个代码示例为第三个代码示例提供了示例 XML 数据。

  • 第五个代码示例演示如何通过将其绑定到 SiteMapDataSource 控件而将 TreeView 控件用于站点导航。

  • 第六个代码示例为第五个代码示例提供了示例站点地图数据。

  • 第七个代码示例演示如何从客户端填充 TreeView 控件中的节点。

下面的代码示例演示如何为它下面的代码示例设置框架。

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

下面的代码示例演示如何使用声明性语法在 TreeView 控件中显示静态数据。在前面示例的框架集中使用此示例来显示目录。

Visual Basic
<%@ Page Language="VB" %>

<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>
C#
<%@ 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>

下面的代码示例演示如何将 TreeView 控件绑定到 XML 数据源。为使此示例正确运行,必须将此代码示例后面提供的示例 XML 数据复制到名为 Book.xml 的文件中。

Visual Basic
<%@ Page Language="VB" %>

<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>
C#
<%@ 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>

下面的代码示例为前面的示例提供了示例 XML 数据。

<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>

下面的代码示例演示如何通过将其绑定到 SiteMapDataSource 控件而将 TreeView 控件用于站点导航。若要此示例正确运行,您必须将在此代码示例之后提供的示例站点地图数据复制到名为 Web.sitemap 的文件中。

Visual Basic
<%@ Page Language="VB" %>

<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>
C#
<%@ 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>

下面的代码示例为前面的代码示例提供了示例站点地图数据。

<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>

下面的代码示例演示如何从客户端填充 TreeView 控件中的节点。启用了客户端节点填充后,会在客户端上自动填充节点,无需回发到服务器。

Visual Basic
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">

  Sub PopulateNode(ByVal sender As Object, ByVal e As TreeNodeEventArgs)

    ' Call the appropriate method to populate a node at a particular level.
    Select Case e.Node.Depth

      Case 0
        ' Populate the first-level nodes.
        PopulateCategories(e.Node)

      Case 1
        ' Populate the second-level nodes.
        PopulateProducts(e.Node)

      Case Else
        ' Do nothing.

    End Select

  End Sub

  Sub PopulateCategories(ByVal node As TreeNode)

    ' Query for the product categories. These are the values
    ' for the second-level nodes.
    Dim ResultSet As DataSet = RunQuery("Select CategoryID, CategoryName From Categories")

    ' Create the second-level nodes.
    If ResultSet.Tables.Count > 0 Then

      ' 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.
      Dim row As DataRow

      For Each 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. 
        Dim newNode As TreeNode = 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)

      Next

    End If

  End Sub

  Sub PopulateProducts(ByVal node As TreeNode)

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

    ' Create the third-level nodes.
    If ResultSet.Tables.Count > 0 Then

      ' 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.
      Dim row As DataRow

      For Each row In ResultSet.Tables(0).Rows

        ' Create the new node.
        Dim NewNode As TreeNode = 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)

      Next

    End If

  End Sub

  Function RunQuery(ByVal QueryString As String) As DataSet

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

    Dim DBConnection As SqlConnection = New SqlConnection(ConnectionString)
    Dim DBAdapter As SqlDataAdapter
    Dim ResultsDataSet As DataSet = 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 ex As Exception

      ' Close the database connection if it is still open.
      If DBConnection.State = ConnectionState.Open Then

        DBConnection.Close()

      End If

      Message.Text = "Unable to connect to the database."

    End Try

    Return ResultsDataSet

  End Function

</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>
C#
<%@ 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>
.NET Framework 安全性

继承层次结构

System.Object
   System.Web.UI.Control
     System.Web.UI.WebControls.WebControl
       System.Web.UI.WebControls.BaseDataBoundControl
         System.Web.UI.WebControls.HierarchicalDataBoundControl
          System.Web.UI.WebControls.TreeView
线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。
平台

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

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0
请参见

标记 :


Page view tracker