asp.net2.0从数据库中读取数据生成分层的结构化TreeView

工作需要做一个网站的导航.需要树结构的导航.
导航数中的节点是从数据库中读取(表相关联),并且数中的叶子节点是按照筛选的类型来显示.
如何实现动态的生成树节点,并且能按类型进行筛选叶子节点?
查看TreeView的属性,会发现其中有一项是"PopulatNodesFromClient",意思为:是否尝试从客户端填充节点.
那么看到了解释之后,当然是选择值为:"True".
在给"PopulatNodesFromClient"赋值为"True"之后,在TreeView的属性事件中就有一项为TreeNodePopulate事件,为:正在填充TreeNode时激发某事件,那么在给该事件写方法时,就可以写从数据库中读取相应的子节点内容了.
所以,每当TreeNode增加一个节点时,便激发该事件,以填充其子节点.
在本例子中,只显示2层树结构,
    protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        if (e.Node.ChildNodes.Count == 0)
        {
            switch (e.Node.Depth)
            {
                case 0:
                    PopulateCategories(e.Node);
                    break;
                case 1:
                    PopulateProducts(e.Node);
                    break;
            }
        }
    }

并且,该树还可以进行复选框选择,TreeView中有一项属性为ShowCheckBoxes,选择值为Leaf,这样每个叶子节点就会显示一个复选框.
获取TreeView选择框中被选中的节点代码如下:
            foreach (TreeNode node in TreeView1.CheckedNodes)
            {
                arraystr.Add(node);
            }

该列子的整个代码如下:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default3.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<asp:Label ID="labelStatus" runat="server" Font-Size="12pt" Text="测试测试。" Width="87px"></asp:Label>
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server"
            Width="119px" OnSelectedIndexChanged="Button1_Click" AutoPostBack="True" AppendDataBoundItems="True">
        </asp:DropDownList>
        <asp:Button ID="Button1" runat="server" Text="提交筛选" OnClick="Button1_Click" /><br />
        <asp:Button ID="submitbtn" runat="server" OnClick="submitbtn_Click" Text="提交选择" />
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="清空选择" /><br />
        <asp:Label ID="Label1" runat="server" Text="Label" Width="368px"></asp:Label><br />
        <asp:TreeView ID="TreeView1" runat="server" Font-Size="12pt" MaxDataBindDepth="2"
            OnTreeNodePopulate="TreeView1_TreeNodePopulate" Width="371px" ShowCheckBoxes="Leaf">
            <Nodes>
                <asp:TreeNode PopulateOnDemand="True" Text="产品列表" Value="产品列表"></asp:TreeNode>
            </Nodes>
        </asp:TreeView>
   
    </div>
    </form>
</body>
</html>

using System;
using System.Data;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlCommand sqlQuery = new SqlCommand(
            "Select CategoryName, CategoryID From Categories");
        DataSet resultSet;
        resultSet = RunQuery(sqlQuery);
        DropDownList1.DataSource = resultSet.Tables[0].DefaultView;
        DropDownList1.DataTextField = "CategoryName";
        DropDownList1.DataValueField = "CategoryID";
        DropDownList1.DataBind();
    }
    protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        if (e.Node.ChildNodes.Count == 0)
        {
            switch (e.Node.Depth)
            {
                case 0:
                    PopulateCategories(e.Node);
                    break;
                case 1:
                    PopulateProducts(e.Node);
                    break;
            }
        }
    }

    void PopulateCategories(TreeNode node)
    {
        SqlCommand sqlQuery = new SqlCommand();
        if ((Session["typeorder"] == null) || (Session["typeorder"].ToString() == "All"))
        {
            sqlQuery.CommandText = "Select CategoryName, CategoryID From Categories";
        }
        else
        {
            sqlQuery.CommandText = "Select CategoryName, CategoryID From Categories where CategoryID ='" + Session["typeorder"].ToString()+"'";
        }
        DataSet resultSet;
        resultSet = RunQuery(sqlQuery);
        if (resultSet.Tables.Count > 0)
        {
            foreach (DataRow row in resultSet.Tables[0].Rows)
            {
                TreeNode NewNode = new
                    TreeNode(row["CategoryName"].ToString(),
                    row["CategoryID"].ToString());
                NewNode.PopulateOnDemand = true;
                NewNode.SelectAction = TreeNodeSelectAction.Expand;
                node.ChildNodes.Add(NewNode);
            }
        }
    }

    void PopulateProducts(TreeNode node)
    {
        SqlCommand sqlQuery = new SqlCommand();
        if ((Session["typeorder"] == null) || (Session["typeorder"].ToString() == "All"))
        {
            sqlQuery.CommandText = "Select ProductName From Products " +
    " Where CategoryID = @categoryid";
            sqlQuery.Parameters.Add("@categoryid", SqlDbType.Int).Value =
                node.Value;
        }
        else
        {
        sqlQuery.CommandText = "Select ProductName From Products " +
            " Where CategoryID = @categoryid";
        sqlQuery.Parameters.Add("@categoryid", SqlDbType.Int).Value =
            node.Value;
        }
        DataSet ResultSet = RunQuery(sqlQuery);
        if (ResultSet.Tables.Count > 0)
        {
            foreach (DataRow row in ResultSet.Tables[0].Rows)
            {
                TreeNode NewNode = new
                    TreeNode(row["ProductName"].ToString(),row["ProductName"].ToString(), null, "test.aspx?id=" + row["ProductName"].ToString(), "_blank");
                NewNode.PopulateOnDemand = false;
                NewNode.SelectAction = TreeNodeSelectAction.Expand;
                node.ChildNodes.Add(NewNode);
            }
        }
    }

    private DataSet RunQuery(SqlCommand sqlQuery)
    {
        string connectionString =
            ConfigurationManager.ConnectionStrings
            ["NorthwindConnectionString"].ConnectionString;
        SqlConnection DBConnection =
            new SqlConnection(connectionString);
        SqlDataAdapter dbAdapter = new SqlDataAdapter();
        dbAdapter.SelectCommand = sqlQuery;
        sqlQuery.Connection = DBConnection;
        DataSet resultsDataSet = new DataSet();
        try
        {
            dbAdapter.Fill(resultsDataSet);
        }
        catch
        {
            labelStatus.Text = "Unable to connect to SQL Server.";
        }
        return resultsDataSet;
    }

    protected void submitbtn_Click(object sender, EventArgs e)
    {
        if (TreeView1.CheckedNodes.Count > 0)
        {
            Label1.Text = "你选择了:<br>";
            ArrayList arraystr = new ArrayList();
            foreach (TreeNode node in TreeView1.CheckedNodes)
            {
                arraystr.Add(node);
            }
            if (Session["selectednodes"] != null)
            {
                ArrayList arraystrswitch = new ArrayList();
                arraystrswitch = (ArrayList)Session["selectednodes"];
                for (int m = 0; m < arraystr.Count; m++)
                {
                    arraystrswitch.Add((TreeNode)arraystr[m]);
                }
                Session["selectednodes"] = arraystrswitch;
            }
            else
            {
                Session["selectednodes"] = arraystr;
            }


            for(int k=0;k<arraystr.Count;k++)
            {
                Label1.Text += ((TreeNode)arraystr[k]).Value + "<br>";
            }
        }
        else
        {
            if (Session["selectednodes"] != null)
            {
                //Label1.Text = Session["selectednodes"].ToString();
            }
            else
            {
                Label1.Text = "你没有选择任何内容!";
            }
        }

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //DropDownList1.SelectedValue.ToString();
        //TreeView1.CollapseAll();
        Session["typeorder"] = DropDownList1.SelectedItem.Value;
        Response.Redirect("Default3.aspx");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Session["selectednodes"] = "";
        Label1.Text = "";
    }
}

原文地址:https://www.cnblogs.com/chf/p/492221.html