从数据库中得到数据,建立树形结构

数据库设计

首先,我们在SQL SERVER 2000里建立一个表tbTree,表的结构设计如下:
列名 数据类型 描述  长度 主键
ID    Int    节点编号  4    是
ParentID Int 父节点编号  4 
ConText Nvarchar 我们要显示的节点内容 50 

在SQL SERVER 2000中建表的脚本:

数据库代码
 1 CREATE TABLE [dbo].[tbTree] (
 2     [ID] [int] IDENTITY (1, 1) NOT NULL ,
 3     [Context] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
 4     [ParentID] [int] NULL
 5 ) ON [PRIMARY]
 6 
 7 //添加记录
 8 
 9 SET IDENTITY_INSERT tbtree ON
10 insert tbtree (ID,Context,ParentID)  values ( 1,'中国',0)
11 insert tbtree (ID,Context,ParentID)  values ( 2,'北京',11)
12 insert tbtree (ID,Context,ParentID)  values ( 3,'天津',11)
13 insert tbtree (ID,Context,ParentID)  values ( 4,'河北省',1)
14 insert tbtree (ID,Context,ParentID)  values ( 5,'广东省',1)
15 insert tbtree (ID,Context,ParentID)  values ( 6,'广州',5)
16 insert tbtree (ID,Context,ParentID)  values ( 7,'四川省',1)
17 insert tbtree (ID,Context,ParentID)  values ( 8,'成都',7)
18 insert tbtree (ID,Context,ParentID)  values ( 9,'深圳',5)
19 insert tbtree (ID,Context,ParentID)  values ( 10,'石家庄',4)
20 insert tbtree (ID,Context,ParentID)  values ( 11,'辽宁省',1)
21 insert tbtree (ID,Context,ParentID)  values ( 12,'大连',11)
22 insert tbtree (ID,Context,ParentID)  values ( 13,'上海',1)
23 insert tbtree (ID,Context,ParentID)  values ( 14,'天河软件园',6)
24 insert tbtree (ID,Context,ParentID)  values ( 15,'汕头',5)
25 SET IDENTITY_INSERT tbtree off
前台代码
 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 2 <HTML>
 3 <HEAD>
 4 <title>WebForm1</title>
 5 <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.0">
 6 <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
 7 <meta name="vs_defaultClientScript" content="JavaScript">
 8 <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 9 </HEAD>
10 <body MS_POSITIONING="GridLayout">
11 <form id="Form1" method="post" runat="server">
12 <FONT face="宋体">
13 <iewc:TreeView id="TreeView1" style="Z-INDEX: 101; LEFT: 39px; TOP: 68px" runat="server"></iewc:TreeView></FONT>
14 </form>
15 </body>
16 </HTML>
后台代码
  1 using System;
  2 using System.Collections;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Web;
  7 using System.Web.SessionState;
  8 using System.Web.UI;
  9 using System.Web.UI.WebControls;
 10 using System.Web.UI.HtmlControls;
 11 using Microsoft.Web.UI.WebControls;
 12 using System.Data.SqlClient;
 13 namespace TreeCS
 14 {
 15     ///
 16     /// WebForm1 的摘要说明
 17     ///
 18     public class WebForm1 : System.Web.UI.Page
 19     {
 20         protected Microsoft.Web.UI.WebControls.TreeView TreeView1;
 21 
 22         private void Page_Load(object sender, System.EventArgs e)
 23         {
 24             // 定义数据库连接
 25             SqlConnection CN = new SqlConnection();
 26             try
 27             {
 28                 //初始化连接字符串
 29                 CN.ConnectionString=
 30                 "data source=pmserver;initial catalog=Benchmark;persist security info=False;user id=sa;Password=sa;";
 31                 CN.Open();
 32 
 33                 SqlDataAdapter adp = new SqlDataAdapter("select * from tbTree",CN);
 34                 DataSet ds=new DataSet();
 35                 adp.Fill(ds);
 36                 this.ViewState["ds"]=ds;
 37             }
 38             catch (Exception ex)
 39             {
 40                 Session["Error"] = ex.ToString();
 41                 Response.Redirect("error.aspx");       //̀跳转程序的公共错误处理页面
 42             }
 43             finally
 44             {
 45                 CN.Close();
 46             }
 47             //调用递归函数,完成树形结构的生成
 48             AddTree(0, (TreeNode)null);
 49         }
 50 
 51         //递归添加树的节点
 52         public void AddTree(int ParentID,TreeNode pNode)
 53         {
 54             DataSet ds=(DataSet) this.ViewState["ds"];
 55             DataView dvTree = new DataView(ds.Tables[0]);
 56             //过滤ParentID,得到当前的所有子节点
 57             dvTree.RowFilter =  "[PARENTID] = " + ParentID;
 58 
 59             foreach(DataRowView Row in dvTree)
 60             {
 61                 TreeNode Node=new TreeNode() ;
 62                 if(pNode == null)
 63                 {    //添加根节点
 64                     Node.Text = Row["ConText"].ToString();
 65                     TreeView1.Nodes.Add(Node);
 66                     Node.Expanded=true;
 67                     AddTree(Int32.Parse(Row["ID"].ToString()), Node);    //再次递归
 68                 }
 69                 else
 70                 {   //̀添加当前节点的子节点
 71                     Node.Text = Row["ConText"].ToString();
 72                     pNode.Nodes.Add(Node);
 73                     Node.Expanded = true;
 74                     AddTree(Int32.Parse(Row["ID"].ToString()),Node);     //再次递归
 75                 }
 76             }
 77         }            
 78 
 79         #region Web Form Designer generated code
 80         override protected void OnInit(EventArgs e)
 81         {
 82             //
 83             // CODEGEN该调用是 ASP.NET Web 窗体设计器所必需的。
 84             //
 85             InitializeComponent();
 86             base.OnInit(e);
 87         }
 88 
 89         /// <summary>
 90         ///设计器支持所需的方法 - 不要使用代码编辑器修改
 91         /// 此方法的内容
 92         /// </summary>
 93         private void InitializeComponent()
 94         {
 95             this.Load += new System.EventHandler(this.Page_Load);
 96 
 97         }
 98         #endregion
 99     }
100 }
原文地址:https://www.cnblogs.com/netalen/p/3019356.html