asp.net中Treeview資料繫結與動態增加節點樣本

來源:互聯網
上載者:User

TreeView資料繫結

在ASP.NET中如何?資料庫與TreeView控制項的資料繫結呢?花些時間自己編寫了一個示範程式,包括有Access資料庫,你可複製這兩個代碼做下測試,測試資料庫檔案後附下載。
Left.aspx 代碼如下:

 代碼如下 複製代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Left.aspx.cs" Inherits="Left" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>示範TreeView資料繫結方法</title>
<script language="javascript">
function chkAll()
{
    var chkall= document.all["chkall"];
    var chkother= document.getElementsByTagName("input");
    for (var i=0;i<chkother.length;i++)
    {
        if( chkother[i].type=='checkbox')
        {
            if(chkother[i].id.indexOf('TreeView1')>-1)
            {
                if(chkall.checked==true)
                {
                    chkother[i].checked=true;
                }
                else
                {
                    chkother[i].checked=false;
                }
            }
        }
    }
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table width=100% height=100%>
    <tr height=10>
        <td><input id="chkall" type="checkbox" onclick="chkAll();" />全選/取消</td>
        <td><asp:Button ID="Button1" runat="server" Text="Button" /></td>
    </tr>
    <tr valign=top>
        <td><asp:TreeView ID="TreeView1" runat="server" ></asp:TreeView></td>
        <td><iframe id=fMain style="BORDER-TOP-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BORDER-BOTTOM-STYLE: none" src="" frameBorder="0" width="100%" scrolling="yes" height="100%"></iframe></td>
    </tr>
    <tr height=10>
        <td></td>
    </tr>
</table>
</form>
</body>
</html>

Left.aspx.cs代碼,與Left.aspx放在同級目錄下:

 代碼如下 複製代碼

using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Left : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindTree();
            //InitTree();
        }
    }
    #region 主從表綁定
    private void BindTree()
    {
        DataSet dst = GetTreeViewData();
        TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
        foreach (DataRow masterRow in dst.Tables["province"].Rows)
        {
            TreeNode masterNode = new TreeNode((string)masterRow["province"]);
            TreeView1.Nodes.Add(masterNode);
            foreach (DataRow childRow in masterRow.GetChildRows("Children"))
            {
                TreeNode childNode =new TreeNode((string)childRow["city"]);
                masterNode.Expanded = false;
                masterNode.ChildNodes.Add(childNode);
            }
        }
    }
    private DataSet GetTreeViewData()
    {
        string constring = System.Configuration.ConfigurationSettings.AppSettings["ConnectionStr"];
        SqlConnection con = new SqlConnection(constring);
        SqlDataAdapter daprovince = new SqlDataAdapter("SELECT * FROM province", con);
        SqlDataAdapter dacity = new SqlDataAdapter("SELECT * FROM city", con);
        DataSet ds = new DataSet();
        daprovince.Fill(ds, "province");
        dacity.Fill(ds, "city");
        ds.Relations.Add("Children", ds.Tables["province"].Columns["provinceid"], ds.Tables["city"].Columns["father"]);
        return ds;
    }
    #endregion
    #region 遞迴綁定同一個表資料
    private void InitTree()
    {
        DataTable dt = GetTreeViewTable();
        DataView dv = new DataView(dt);
        dv.RowFilter = "ParentID=0";
        TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
        foreach (DataRowView drv in dv)
        {
            TreeNode node = new TreeNode();
            node.Text = drv["text"].ToString();
            node.Value = drv["ID"].ToString();
            node.Expanded = false;
            TreeView1.Nodes.Add(node);
            AddReplies(dt,node);
        }
    }
    private DataTable GetTreeViewTable()
    {
        string constring = System.Configuration.ConfigurationSettings.AppSettings["ConnectionStr"];
        SqlConnection con = new SqlConnection(constring);
        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM treeview", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
    private void AddReplies(DataTable dt, TreeNode node)
    {
        DataView dv = new DataView(dt);
        dv.RowFilter = "ParentID='" + node.Value + "'";
        foreach (DataRowView row in dv)
        {
            TreeNode replyNode = new TreeNode();
            replyNode.Text = row["text"].ToString();
            replyNode.Value = row["ID"].ToString();
            replyNode.Expanded = false;
            node.ChildNodes.Add(replyNode);
            AddReplies(dt,replyNode);
        }
    }
    #endregion
}


Treeview動態增加節點執行個體


在asp.net中使用TreeView,如果是靜態增加節點資料,這個很好辦,但一般情況下,TreeView是要動態顯示功能表項目的,大部分都是從XML或Access、SqlServer資料庫中載入內容,要從資料庫中讀出內容動態增加結點,其實也不難,比如以SQL2000的PUBS資料庫為例子,我們以樹型列表方式取出“作者”做為根結點,再取出對應作者的作品作為子節點,來實現動態展開並載入資料的TreeView,我們可以這樣做:

 代碼如下 複製代碼
<%@ Page Language="C#"%>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient"%>
<%@ Import Namespace="System.Configuration"%>
<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Population of the TreeView Control</title>
<script runat=server>
void Node_Populate(object sender,
System.Web.UI.WebControls.TreeNodeEventArgs e)
{
if(e.Node.ChildNodes.Count == 0)
{
switch( e.Node.Depth )
{
case 0:
FillAuthors(e.Node);
break;
case 1:
FillTitlesForAuthors(e.Node);
break;
}
}
}
void FillAuthors(TreeNode node)
{
string connString = System.Configuration.ConfigurationSettings.
ConnectionStrings["NorthwindConnnection"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand command = new SqlCommand("Select * From
authors",connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet authors = new DataSet();
adapter.Fill(authors);
if (authors.Tables.Count > 0)
{
foreach (DataRow row in authors.Tables[0].Rows)
{
TreeNode newNode = new
TreeNode(row["au_fname"].ToString() + " " +
row["au_lname"].ToString(),
row["au_id"].ToString());
newNode.PopulateOnDemand = true;
newNode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(newNode);
}
}
}
void FillTitlesForAuthors(TreeNode node)
{
string authorID = node.Value;
string connString = System.Configuration.ConfigurationSettings.
ConnectionStrings["NorthwindConnnection"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand command = new SqlCommand("Select T.title,
T.title_id From titles T" +
" Inner Join titleauthor TA on
T.title_id = TA.title_id " +
" Where TA.au_id = '" + authorID + "'", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet titlesForAuthors = new DataSet();
adapter.Fill(titlesForAuthors);
if (titlesForAuthors.Tables.Count > 0)
{
foreach (DataRow row in titlesForAuthors.Tables[0].Rows)
{
TreeNode newNode = new TreeNode(
row["title"].ToString(), row["title_id"].ToString());
newNode.PopulateOnDemand = false;
newNode.SelectAction = TreeNodeSelectAction.None;
node.ChildNodes.Add(newNode);
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeViewRunat="Server" ExpandImageUrl="Images/closed.gif"
CollapseImageUrl="Images/open.gif"
OnTreeNodePopulate="Node_Populate" ID="tvwauthors">
<Nodes>
<asp:TreeNodeText="Authors" PopulateOnDemand=true
Value="0"/>
</Nodes>
</asp:TreeView>
</div>
</form>
</body>
</html>

其中,要注意ontreenodepopulate事件,是在展開樹結點時發生的,這裡自訂了node_populate來檢查當前結點的深度,如果是0,就是根結點,於是就調用FillAuthors過程,取出所有的作者,如果深度是1,則是子節點,調用FillTitlesForAuthors過程讀取作品資訊。其中,要注意動態建立樹結點的過程,如下代碼:

 代碼如下 複製代碼
TreeNode newNode = new TreeNode(row["au_fname"].ToString() + " " +
row["au_lname"].ToString(),
row["au_id"].ToString());
newNode.PopulateOnDemand = true;
newNode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(newNode);

從popluateondemand的屬性來看,該節點可以動態擴充。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.