zoukankan      html  css  js  c++  java
  • .NET平台下Web树形结构程序设计李洪根

    我的上篇文章《树形结构在开发中的应用》主要是在Windows Form下的实现,下面讲一下Web Form下的实现。

    概述

    TreeView是一个重要的控件,无论是在VB.NET,C# 还是VB、Delphi等各种语言中,都充当了导航器的作用。在实际工作中,很多情况下需要将TreeView与数据库进行连接,以填充其节点。在Windows Form和Web Form中,我们可以用TreeView来显示树形结构,如显示目录树、显示地区、分类显示商品等。可以说,在大部分软件的开发中,TreeView都是一个不可缺少的展示控件。因此,树形结构的设计就成了软件开发人员一个永恒的话题。
    树形结构的展示方式
    树形结构的展示一般来讲有三种方式:
    1.界面设计时在TreeView设计器或者代码中直接填充TreeView控件。
    2.从XML文件中建立树形结构。
    3.从数据库中得到数据,建立树形结构。
    第一种方式是最简单的,这种方式主要用于树形结构一般没有变化的应用程序,在设计时就固定一颗树。当然,在设计时固定了树的结构,以后要想修改、增加、删除树的节点,就必须修改源程序。所有不利于扩展。
    第二种方式从XML文件中提取,由于XML本身就是树形结构的,微软提供的文档对象模型DOM 可以方便的读取、操作和修改 XML 文档。在.NET中,应用System.Xml类可以方便地将XML文件加载到TreeView控件中,微软的MSDN也提供了实例,此处就不再多说。
    第三种方式,树形结构的数据,从数据库中获得。一般来讲,我们的应用程序多数是基于数据库的。采用这种方式,增加、修改、删除一颗树的节点很方便,只要操作数据库中的数据就可以了。而且,这种方式可以和数据库中的其它表做关联、查询和汇总,通过设计视图或存储过程,很容易查询出你想要的相关数据。下面,我们主要讨论这种方式的设计和实现。

    数据库设计

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

    在SQL SERVER 2000中建表的脚本:
    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
    




    下载地址 http://msdn.microsoft.com/downloads/samples/internet/ASP_DOT_NET_ServerControls/WebControls/default.asp 安装后,通过“自定义工具箱”->“.net框架组件”把TreeView添加到工具箱里。 新建一个项目,选择Visual Basic.Net 工程Asp.net Web应用程序,在页面上拖画一个TreeView控件。 Html页:
    <%@ 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>
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim 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") = ds
            Catch ex As Exception
    #If DEBUG Then
                Session("Error") = ex.ToString()
                Response.Redirect("error.aspx")        '̀跳转程序的公共错误处理页面
    #End If
            Finally
                '关闭连接
                CN.Close()
            End Try
            '调用递归函数,完成树形结构的生成
            AddTree(0, Nothing)
        End Sub
    
        '递归添加树的节点
        Private Sub AddTree(ByVal ParentID As Integer, ByVal pNode As TreeNode)
            Dim ds As DataSet
            ds = Me.ViewState("ds")
            Dim dvTree As New DataView()
            dvTree = New DataView(ds.Tables(0))
            '过滤ParentID,得到当前的所有子节点
            dvTree.RowFilter = "PARENTID = " + ParentID.ToString
    
            Dim Row As DataRowView
            For Each Row In dvTree
                Dim Node As New TreeNode()
                If pNode Is Nothing Then  '判断是否根节点
                    '添加根节点
                    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.Nodes.Add(Node)
                    Node.Expanded = True
                    '再次递归
                    AddTree(Int32.Parse(Row("ID").ToString()), Node)
                End If
            Next
        End Sub
    
    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.Nodes.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
    	}
    }
    







  • 相关阅读:
    Atitit. visual studio vs2003 vs2005 vs2008  VS2010 vs2012 vs2015新特性 新功能.doc
    Atitit. C#.net clr 2.0  4.0新特性
    Atitit. C#.net clr 2.0  4.0新特性
    Atitit.通过null 参数 反射  动态反推方法调用
    Atitit.通过null 参数 反射  动态反推方法调用
    Atitit..net clr il指令集 以及指令分类  与指令详细说明
    Atitit..net clr il指令集 以及指令分类  与指令详细说明
    Atitit.变量的定义 获取 储存 物理结构 基本类型简化 隐式转换 类型推导 与底层原理 attilaxDSL
    Atitit.变量的定义 获取 储存 物理结构 基本类型简化 隐式转换 类型推导 与底层原理 attilaxDSL
    Atitit.跨语言反射api 兼容性提升与增强 java c#。Net  php  js
  • 原文地址:https://www.cnblogs.com/goody9807/p/184754.html
Copyright © 2011-2022 走看看