asp.net2.0從資料庫中讀取資料產生分層的結構化TreeView

來源:互聯網
上載者:User

工作需要做一個網站的導航.需要樹結構的導航.
導航數中的節點是從資料庫中讀取(表相關聯),並且數中的葉子節點是按照篩選的類型來顯示.
如何?動態產生樹節點,並且能按類型進行篩選葉子節點?
查看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 = "";
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.