VS.Net2005里的TreeView

与以前IEwebcontrol里的TreeView差别挺大,这两天正在做基于Asp.net 2.0 AJAX的树形菜单!

TreeView Web 服务器控件可以显示各种不同类型的数据:控件中以声明方式指定的静态数据;绑定到该控件的数据;或为响应用户操作而动态添加到 TreeView 控件中的数据。

显示静态数据

最简单的数据架构是声明性静态数据。若要使用声明性语法显示静态数据,请创建一个 TreeView 控件子级节点的集合。

下面的示例演示如何示包含三个节点(其中两个节点有子节点)的 TreeView 控件。

 
<asp:TreeView ID="TreeView1" Runat="server">
<Nodes>
<asp:TreeNode Value="Parent1" Expanded="True" Text="1">
<asp:TreeNode Value="Child1A" Text="A" />
<asp:TreeNode Value="Child1B" Text="B" />
</asp:TreeNode>
<asp:TreeNode Value="Parent2" Text="2">
</asp:TreeNode>
<asp:TreeNode Value="Parent3" Expanded="True" Text="3">
<asp:TreeNode Value="Child3A" Text="A">
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>

绑定到数据源

若要显示以声明方式绑定到该控件的数据,请首先向页面添加一个分层数据源控件(如 XmlDataSource 控件),并向该控件分配一个 ID 。然后,将 TreeView 控件的 DataSourceID 属性设置为该数据源控件的 ID。TreeView 控件即可自动绑定到数据源并显示数据源的值。

注意

TreeView 控件可以绑定到实现 IHierarchicalDataSource 接口的任何数据源控件,如 SiteMapDataSource 对象或 XmlDataSource 对象。

默认情况下,在绑定一个数据源时,如果该数据源的每个数据项包含多个属性(如一个 XML 元素具有多个属性),则节点显示数据项的 ToString 方法所返回的值。就 XML 元素而言,节点显示该元素名称。此架构显示了树的基础结构,但在其他方面不是很有用。可以通过使用 DataBindings 集合指定树节点绑定,从而将节点绑定到特定数据项属性。DataBindings 集合包含定义数据项和它所绑定到的节点之间的关系的 TreeNodeBinding 对象。可以指定绑定条件和要显示在节点中的数据项属性。有关树节点绑定的更多信息,请参见 TreeNodeBinding。

注意

此外,TreeView 控件还为手动数据绑定提供了一个 DataSource 属性和一个 DataBind 方法。

动态显示数据

可能无法以静态方式定义数据结构,或数据可能依赖于运行时收集的信息。可以在服务器端代码中以编程方式将 TreeNode 对象填充到 TreeView 控件的 Nodes 集合中,也可以利用 TreeView 控件的 PopulateOnDemand 功能在客户端上的父节点展开时动态填充节点。有关更多信息,请参见将数据绑定到 TreeView Web 服务器控件

有时,静态地预定义树结构并不可行,因为有时数据大小或自定义内容依用户输入而定。因此,TreeView 控件支持动态节点填充。如果将某节点的 PopulateOnDemand 属性设置为 true,则展开该节点后在运行时填充该节点。

若要动态填充某个节点,请首先将该节点的 PopulateOnDemand 属性设置为 true。然后,为以编程方式填充节点的 TreeNodePopulate 事件定义一个事件处理方法。通常的事件处理方法会从数据源中检索节点数据,将该数据放入一个节点结构中,然后将该节点结构添加到正在被填充的节点的 ChildNodes 集合中。通过将 TreeNode 对象添加到父节点的 ChildNodes 集合中,可以创建一个节点结构。

当节点的 PopulateOnDemand 属性设置为 true 时,必须动态填充该节点。不能以声明方式将另一节点嵌套在它的下面;否则将会在页面上出现一个错误。

受支持的浏览器(Microsoft Internet Explorer 版本 4.0 和更高版本的兼容浏览器)还可以利用客户端节点填充。启用后,将允许 TreeView 控件在节点展开时在客户端上动态填充该节点,这样就不需要回发到服务器。有关客户端节点填充的更多信息,请参见 PopulateNodesFromClient

有关处理事件的更多信息,请参见 使用事件

的代码示例演示如何使用 TreeNodePopulate 事件动态地在服务器上填充 TreeView 控件中的节点。请注意,将 EnableClientScript 属性设置为 false 可以防止在客户端上处理展开节点事件。
Visual Basic 

CopyCode image复制代码

<%@ 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(row("CategoryName").ToString(), 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 TreeNodePopulate Example</h3>

    

      <asp:TreeView id="LinksTreeView"

        Font-Name= "Arial"

        ForeColor="Blue"

        EnableClientScript="false" 

        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(row["CategoryName"].ToString(), 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 TreeNodePopulate Example</h3>

<asp:TreeView id="LinksTreeView"
Font-Name= "Arial"
ForeColor="Blue"
EnableClientScript="false"
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>


你可能感兴趣的:(treeview)