1:建立数据库
在SQL SERVER 2000里建立一个表tbTree,表的结构设计如下:
列名 数据类型 描述 长度 主键
ID Int 节点编号 4 是
ParentID Int 父节点编号 4
ConText Nvarchar 我们要显示的节点内容 50
在SQL SERVER 2000中建表的脚本:
CREATE TABLE [dbo].[tbTree] (
[ID] [int] NOT NULL ,
[Context] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[ParentID] [int] NULL
) ON [PRIMARY]
在表中添加如下记录:
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)
**********************************************************************
2.添加一个新页面,放置一个TreeView控件
3.页面代码如下:主要是用到了递归算法
DataSet
ds = new DataSet();
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
//
在此处放置用户代码以初始化页面
SqlConnection CN = new SqlConnection();
try
{
//
初始化连接字符串
CN.ConnectionString = "Data Source=A21D1656E2B7442//SQL2000;Initial Catalog=xiazai;Integrated Security=True";
CN.Open();
//
添加命令,从数据库中得到数据
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = CN;
sqlCmd.CommandText = "select * from tbTree";
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter(sqlCmd);
adp.Fill(ds);
}
catch (Exception ex)
{
throw (ex);
}
finally
{
CN.Close();
}
//
调用递归函数,完成树形结构的生成
//tn2=AddTree(0, (TreeNode)null);
//TreeView1.Nodes.Add(tn2);
AddTree(0, (TreeNode)null);
}
}
public void AddTree(int ParentID, TreeNode pNode)
{
TreeNode tn1 = new TreeNode();
DataView dvTree = new DataView(ds.Tables[0]);
//
过滤ParentID,得到当前的所有子节点
dvTree.RowFilter = "[PARENTID] = " + ParentID;
foreach (DataRowView Row in dvTree)
{
if (pNode == null)
{ //'?
添加根节点
tn1.Text = Row["ConText"].ToString();
TreeView1.Nodes.Add(tn1);
tn1.Expanded = true;
AddTree(Int32.Parse(Row["ID"].ToString()), tn1); //
再次递归
}
else
{ //
添加当前节点的子节点
TreeNode tn2 = new TreeNode();
tn2.Text = Row["ConText"].ToString();
//pNode.Nodes.Add(tn2);
pNode.ChildNodes.Add(tn2);
tn1.Expanded = true;
AddTree(Int32.Parse(Row["ID"].ToString()), tn2); //
再次递归
}
}
}