概述
TreeView是一個(gè)重要的控件,無論是在VB.NET,C# 還是VB、Delphi等各種語(yǔ)言中,都充當(dāng)了導(dǎo)航器的作用。在實(shí)際工作中,很多情況下需要將TreeView與數(shù)據(jù)庫(kù)進(jìn)行連接,以填充其節(jié)點(diǎn)。在Windows Form和Web Form中,我們可以用TreeView來顯示樹形結(jié)構(gòu),如顯示目錄樹、顯示地區(qū)、分類顯示商品等??梢哉f,在大部分軟件的開發(fā)中,TreeView都是一個(gè)不可缺少的展示控件。因此,樹形結(jié)構(gòu)的設(shè)計(jì)就成了軟件開發(fā)人員一個(gè)永恒的話題。
樹形結(jié)構(gòu)的展示方式
樹形結(jié)構(gòu)的展示一般來講有三種方式:
1.界面設(shè)計(jì)時(shí)在TreeView設(shè)計(jì)器或者代碼中直接填充TreeView控件。
2.從XML文件中建立樹形結(jié)構(gòu)。
3.從數(shù)據(jù)庫(kù)中得到數(shù)據(jù),建立樹形結(jié)構(gòu)。
第一種方式是最簡(jiǎn)單的,這種方式主要用于樹形結(jié)構(gòu)一般沒有變化的應(yīng)用程序,在設(shè)計(jì)時(shí)就固定一顆樹。當(dāng)然,在設(shè)計(jì)時(shí)固定了樹的結(jié)構(gòu),以后要想修改、增加、刪除樹的節(jié)點(diǎn),就必須修改源程序。所有不利于擴(kuò)展。
第二種方式從XML文件中提取,由于XML本身就是樹形結(jié)構(gòu)的,微軟提供的文檔對(duì)象模型DOM 可以方便的讀取、操作和修改 XML 文檔。在.NET中,應(yīng)用System.Xml類可以方便地將XML文件加載到TreeView控件中,微軟的MSDN也提供了實(shí)例,此處就不再多說。
第三種方式,樹形結(jié)構(gòu)的數(shù)據(jù),從數(shù)據(jù)庫(kù)中獲得。一般來講,我們的應(yīng)用程序多數(shù)是基于數(shù)據(jù)庫(kù)的。采用這種方式,增加、修改、刪除一顆樹的節(jié)點(diǎn)很方便,只要操作數(shù)據(jù)庫(kù)中的數(shù)據(jù)就可以了。而且,這種方式可以和數(shù)據(jù)庫(kù)中的其它表做關(guān)聯(lián)、查詢和匯總,通過設(shè)計(jì)視圖或存儲(chǔ)過程,很容易查詢出你想要的相關(guān)數(shù)據(jù)。下面,我們主要討論這種方式的設(shè)計(jì)和實(shí)現(xiàn)。
數(shù)據(jù)庫(kù)設(shè)計(jì)
首先,我們?cè)赟QL SERVER 2000里建立一個(gè)表tbTree,表的結(jié)構(gòu)設(shè)計(jì)如下:
列名 數(shù)據(jù)類型 描述 長(zhǎng)度 主鍵
ID Int 節(jié)點(diǎn)編號(hào) 4 是
ParentID Int 父節(jié)點(diǎn)編號(hào) 4
ConText Nvarchar 我們要顯示的節(jié)點(diǎn)內(nèi)容 50
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 ONinsert tbtree (ID,Context,ParentID) values ( 1,'中國(guó)',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下載地址
http://msdn.microsoft.com/downloads/samples/internet/ASP_DOT_NET_ServerControls/WebControls/default.asp
安裝后,通過“自定義工具箱”->“.net框架組件”把TreeView添加到工具箱里。
新建一個(gè)項(xiàng)目,選擇Visual Basic.Net 工程Asp.net Web應(yīng)用程序,在頁(yè)面上拖畫一個(gè)TreeView控件。Html頁(yè):<%@ Register TagPrefix="iewc" Namespace="Microsoft.Web.UI.WebControls" Assembly="Microsoft.Web.UI.WebControls, Version=1.0.2.226, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %><%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="Tree.WebForm1"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><title>WebForm1</title><meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.0"><meta name="CODE_LANGUAGE" content="Visual Basic 7.0"><meta name="vs_defaultClientScript" content="JavaScript"><meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"></HEAD><body MS_POSITIONING="GridLayout"><form id="Form1" method="post" runat="server"><FONT face="宋體"><iewc:TreeView id="TreeView1" style="Z-INDEX: 101; LEFT: 39px; TOP: 68px" runat="server"></iewc:TreeView></FONT></form></body></HTML>后臺(tái)代碼:Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadDim ds As New DataSet()Dim CN As New SqlConnection()Try'初始化連接字符串CN.ConnectionString ="data source=pmserver;initial catalog=Benchmark;persist security info=False;user id=sa;Password=sa;"CN.Open()Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from tbTree", CN)adp.Fill(ds)Me.ViewState("ds") = dsCatch ex As Exception#If DEBUG ThenSession("Error") = ex.ToString()Response.Redirect("error.aspx") '?跳轉(zhuǎn)程序的公共錯(cuò)誤處理頁(yè)面#End IfFinally'關(guān)閉連接CN.Close()End Try'調(diào)用遞歸函數(shù),完成樹形結(jié)構(gòu)的生成AddTree(0, Nothing)End Sub'遞歸添加樹的節(jié)點(diǎn)Private Sub AddTree(ByVal ParentID As Integer, ByVal pNode As TreeNode)Dim ds As DataSetds = Me.ViewState("ds")Dim dvTree As New DataView()dvTree = New DataView(ds.Tables(0))'過濾ParentID,得到當(dāng)前的所有子節(jié)點(diǎn)dvTree.RowFilter = "PARENTID = " + ParentID.ToStringDim Row As DataRowViewFor Each Row In dvTreeDim Node As New TreeNode()If pNode Is Nothing Then '判斷是否根節(jié)點(diǎn)'添加根節(jié)點(diǎn)Node.Text = Row("ConText").ToString()TreeView1.Nodes.Add(Node)Node.Expanded = True'再次遞歸AddTree(Int32.Parse(Row("ID").ToString()), Node)Else'?添加當(dāng)前節(jié)點(diǎn)的子節(jié)點(diǎn)Node.Text = Row("ConText").ToString()pNode.Nodes.Add(Node)Node.Expanded = True'再次遞歸AddTree(Int32.Parse(Row("ID").ToString()), Node)End IfNextEnd SubC#版本: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){// 定義數(shù)據(jù)庫(kù)連接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"); //?跳轉(zhuǎn)程序的公共錯(cuò)誤處理頁(yè)面}finally{CN.Close();}//調(diào)用遞歸函數(shù),完成樹形結(jié)構(gòu)的生成AddTree(0, (TreeNode)null);}//遞歸添加樹的節(jié)點(diǎn)public void AddTree(int ParentID,TreeNode pNode){DataSet ds=(DataSet) this.ViewState["ds"];DataView dvTree = new DataView(ds.Tables[0]);//過濾ParentID,得到當(dāng)前的所有子節(jié)點(diǎn)dvTree.RowFilter = "[PARENTID] = " + ParentID;foreach(DataRowView Row in dvTree){TreeNode Node=new TreeNode() ;if(pNode == null){ //添加根節(jié)點(diǎn)Node.Text = Row["ConText"].ToString();TreeView1.Nodes.Add(Node);Node.Expanded=true;AddTree(Int32.Parse(Row["ID"].ToString()), Node); //再次遞歸}else{ //?添加當(dāng)前節(jié)點(diǎn)的子節(jié)點(diǎn)Node.Text = Row["ConText"].ToString();pNode.Nodes.Add(Node);Node.Expanded = true;AddTree(Int32.Parse(Row["ID"].ToString()),Node); //再次遞歸}}}#region Web Form Designer generated codeoverride protected void OnInit(EventArgs e){//// CODEGEN該調(diào)用是 ASP.NET Web 窗體設(shè)計(jì)器所必需的。//InitializeComponent();base.OnInit(e);}/// <summary>///設(shè)計(jì)器支持所需的方法 - 不要使用代碼編輯器修改/// 此方法的內(nèi)容/// </summary>private void InitializeComponent(){this.Load += new System.EventHandler(this.Page_Load);}#endregion}}后記:請(qǐng)讀者自行修改程序中的連接字符串設(shè)置。
附:相關(guān)微軟MSDN文檔,包括在VB6和.NET中從XML建立樹形結(jié)構(gòu)
http://support.microsoft.com/default.aspx?kbid=311318
http://support.microsoft.com/default.aspx?kbid=308063
http://support.microsoft.com/default.aspx?kbid=317597
http://support.microsoft.com/default.aspx?kbid=244954
聯(lián)系客服