asp.net中treeview数据绑定_asp.net中Treeview数据绑定与动态增加节点示例

更新时间:2019-07-10    来源:Access    手机版     字体:

【www.bbyears.com--Access】

TreeView数据绑定

在ASP.NET中如何实现数据库与TreeView控件的数据绑定呢?花些时间自己编写了一个演示程序,包括有Access数据库,你可复制这两个代码做下测试,测试数据库文件后附下载。
Left.aspx 代码如下:

 代码如下

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Left.aspx.cs" Inherits="Left" %>


演示TreeView数据绑定方法
<script language="javascript">
function chkAll()
{
    var chkall= document.all["chkall"];
    var chkother= document.getElementsByTagName("input");
    for (var i=0;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>




   
        全选/取消
       
   
   
       
       
   
   
       
   



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



Dynamic Population of the TreeView Control
<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>




CollapseImageUrl="Images/open.gif"
OnTreeNodePopulate="Node_Populate" ID="tvwauthors">

Value="0"/>






其中,要注意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的属性来看,该节点可以动态扩展。

本文来源:http://www.bbyears.com/shujuku/57234.html