程序代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tree.aspx.cs" Inherits="Tree" %>
<!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>
<asp:TreeView ID="tvGroupData" runat="server" ImageSet="XPFileExplorer" ShowLines="True" ShowCheckBoxes="Leaf">
</asp:TreeView>
</div>
</form>
</body>
</html>
Tree.aspx.cs
程序代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
public partial class Tree : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindTreeView("PageFrameSpace", GetTreeViewTable());
}
}
#region 递归绑定树形目录
#endregion
private DataTable GetTreeViewTable()
{
DataTable dtProduct = objDB.GetDataTable("basGetGroupData", null);
return dtProduct;
}
#region BindTreeView
//邦定根节点
public void BindTreeView(string TargetFrame, DataTable dt)
{
DataRow[] drs = dt.Select("ParentNo= " + 0);// 选出所有子节点
tvGroupData.Nodes.Clear(); // 清空树
foreach (DataRow r in drs)
{
string nodeid = r["GroupNo"].ToString();
string text = r["GroupName"].ToString();
string parentid = r["ParentNo"].ToString();
string url = "UserData.aspx?strgroupno=" + r["GroupNo"].ToString();
string framename = TargetFrame;
this.tvGroupData.Font.Name = "宋体";
this.tvGroupData.Font.Size = FontUnit.Parse("9");
TreeNode rootnode = new TreeNode();
rootnode.Text = text;
rootnode.Value = nodeid;
rootnode.NavigateUrl = url;
rootnode.Target = framename;
//rootnode.SelectAction = TreeNodeSelectAction.Expand;//和ASP.NET1.1中TREEVIEW的SelectExpands属性等效
rootnode.SelectAction = TreeNodeSelectAction.None;
rootnode.Expanded = true;
tvGroupData.Nodes.Add(rootnode);
int sonparentid = int.Parse(nodeid);// or =location
CreateNode(framename, sonparentid, rootnode, dt);
}
}
// }
//邦定任意节点
public void CreateNode(string TargetFrame, int parentno, TreeNode parentnode, DataTable dt)
{
DataRow[] drs = dt.Select("ParentNo= " + parentno);//选出所有子节点
// tvGroupData.ShowCheckBoxes = TreeNodeTypes.Parent;
foreach (DataRow r in drs)
{
string nodeid = r["GroupNo"].ToString();
string text = r["GroupName"].ToString();
string url = "UserData.aspx?strgroupno=" + r["GroupNo"].ToString();
string framename = TargetFrame;
TreeNode node = new TreeNode();
node.Text = text;
node.Value = nodeid;
node.NavigateUrl = url;
node.Target = TargetFrame;
//node.SelectAction = TreeNodeSelectAction.Expand; //和ASP.NET1.1中TREEVIEW的SelectExpands属性等效
node.Expanded = true;
int sonparentid = int.Parse(nodeid);// or =location
if (parentnode == null)
{
tvGroupData.Nodes.Clear();
parentnode = new TreeNode();
tvGroupData.Nodes.Add(parentnode);
}
parentnode.ChildNodes.Add(node);
CreateNode(framename, sonparentid, node, dt);
// }//endif
}//endforeach
}
#endregion
}
}
引用内容
程序代码 <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</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" οnclick="chkAll();" />全选/取消</td>
</tr>
</table>
</form>
</body>
</html>
//cs********************************
程序代码 protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//BindTree();
InitTree();
//this.TreeView1.Attributes.Add("ondragstart", "nodeclick();");
this.TreeView1.Attributes.Add("onclick", "return tree_oncheck(this);");
}
}
#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["ConnectionString"];
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["Subject"].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["ConnectionString"];
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter("Select * FROM tree", 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 drv in dv)
{
TreeNode replyNode = new TreeNode();
replyNode.Text = drv["Subject"].ToString();
replyNode.Value = drv["ID"].ToString();
replyNode.Expanded = false;
node.ChildNodes.Add(replyNode);
AddReplies(dt,replyNode);
}
}
#endregion
创建表结构
程序代码 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Tree]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Tree]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[city]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[city]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[province]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[province]
GO
Create TABLE [dbo].[Tree] (
[ID] [int] NULL ,
[ParentID] [int] NULL ,
[Subject] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
[Url] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
Create TABLE [dbo].[city] (
[id] [int] NOT NULL ,
[cityID] [nvarchar] (6) COLLATE Chinese_PRC_CI_AS NULL ,
[city] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[father] [nvarchar] (6) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
Create TABLE [dbo].[province] (
[id] [int] NOT NULL ,
[provinceID] [nvarchar] (6) COLLATE Chinese_PRC_CI_AS NULL ,
[province] [nvarchar] (40) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
引用内容
http://www.microsoft.com/china/community/Column/30.mspx
在2005里 把这句话//pNode.Nodes.Add(Node);改成pNode.ChildNodes.Add(Node);就可以了,测试过OK
===============================================================
创建表结构
程序代码 Create TABLE [dbo].[tbTree] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[Context] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[ParentID] [int] NULL
) ON [PRIMARY]
填充数据
程序代码 SET IDENTITY_Insert tbtree ON
insert tbtree (ID,Context,ParentID) values ( 1,'中国',0)
insert tbtree (ID,Context,ParentID) values ( 2,'北京',11)
insert tbtree (ID,Context,ParentID) values ( 3,'天津',11)
insert tbtree (ID,Context,ParentID) values ( 4,'河北省',1)
insert tbtree (ID,Context,ParentID) values ( 5,'广东省',1)
insert tbtree (ID,Context,ParentID) values ( 6,'广州',5)
insert tbtree (ID,Context,ParentID) values ( 7,'四川省',1)
insert tbtree (ID,Context,ParentID) values ( 8,'成都',7)
insert tbtree (ID,Context,ParentID) values ( 9,'深圳',5)
insert tbtree (ID,Context,ParentID) values ( 10,'石家庄',4)
insert tbtree (ID,Context,ParentID) values ( 11,'辽宁省',1)
insert tbtree (ID,Context,ParentID) values ( 12,'大连',11)
insert tbtree (ID,Context,ParentID) values ( 13,'上海',1)
insert tbtree (ID,Context,ParentID) values ( 14,'天河软件园',6)
insert tbtree (ID,Context,ParentID) values ( 15,'汕头',5)
SET IDENTITY_Insert tbtree off
程序代码
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.Web.UI.WebControls;
using System.Data.SqlClient;
namespace TreeCS
{
///
/// WebForm1 的摘要说明
///
public class WebForm1 : System.Web.UI.Page
{
protected Microsoft.Web.UI.WebControls.TreeView TreeView1;
private void Page_Load(object sender, System.EventArgs e)
{
// 定义数据库连接
SqlConnection CN = new SqlConnection();
try
{
//初始化连接字符串
CN.ConnectionString=
"data source=pmserver;initial catalog=Benchmark;persist security info=False;user id=sa;Password=sa;";
CN.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from tbTree",CN);
DataSet ds=new DataSet();
adp.Fill(ds);
this.ViewState["ds"]=ds;
}
catch (Exception ex)
{
Session["Error"] = ex.ToString();
Response.Redirect("error.aspx"); //̀跳转程序的公共错误处理页面
}
finally
{
CN.Close();
}
//调用递归函数,完成树形结构的生成
AddTree(0, (TreeNode)null);
}
//递归添加树的节点
public void AddTree(int ParentID,TreeNode pNode)
{
DataSet ds=(DataSet) this.ViewState["ds"];
DataView dvTree = new DataView(ds.Tables[0]);
//过滤ParentID,得到当前的所有子节点
dvTree.RowFilter = "[PARENTID] = " + ParentID;
foreach(DataRowView Row in dvTree)
{
TreeNode Node=new TreeNode() ;
if(pNode == null)
{ //添加根节点
Node.Text = Row["ConText"].ToString();
TreeView1.Nodes.Add(Node);
Node.Expanded=true;
AddTree(Int32.Parse(Row["ID"].ToString()), Node); //再次递归
}
else
{ //̀添加当前节点的子节点
Node.Text = Row["ConText"].ToString();
pNode.ChildNodes.Add(Node);
Node.Expanded = true;
AddTree(Int32.Parse(Row["ID"].ToString()),Node); //再次递归
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
///设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
转载于:https://www.cnblogs.com/dnmidi/archive/2007/12/01/979710.html