ASP.NET 2.0 中如何把在数据库读取出来的节点在TreeView中无限添加

njlywy 2009-11-10 10:24:12
sql2005数据库
数据库:Node

nodeId nodeText parentNodeId
1 A 0
2 B 0
3 C 0
4 A1 1
5 B1 2
6 C1 3
7 A11 4
8 A12 4
9 B11 5
10 B12 5
11 C11 6
12 C12 6

用winForm或者Web程序都可以,请给出具体的算法,解释,以及完整的程序,谢谢~~

可以加我的QQ:17651854
...全文
196 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
njlyzh 2009-11-11
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 njlywy 的回复:]
引用 3 楼 jack15850798154 的回复:
在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,'北京',1)

insert tbtree (ID,Context,ParentID)  values ( 3,'天津',1)

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


下载Treeview控件地址
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


C#版本:

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
{
      /// <summary>
      /// WebForm1 的摘要说明
      /// </summary>
      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
      }
}



程序报错,说:
else
                            {  //?添加当前节点的子节点
                                  Node.Text = Row["ConText"].ToString();
                                  pNode.Nodes.Add(Node);
                                  Node.Expanded = true;
                                  AddTree(Int32.Parse(Row["ID"].ToString()),Node);    //再次递归
                            }
错误:“System.Web.UI.WebControls.TreeNode”并不包含“Nodes”的定义
错误指向pNode.Nodes.Add(Node);
解决下谢谢~~
[/Quote]


改成:pNode.ChildNodes.Add(Node);
jack15850798154 2009-11-10
  • 打赏
  • 举报
回复



在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,'北京',1)

insert tbtree (ID,Context,ParentID) values ( 3,'天津',1)

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


下载Treeview控件地址
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


C#版本:

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
{
/// <summary>
/// WebForm1 的摘要说明
/// </summary>
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
}
}
njlywy 2009-11-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 zgke 的回复:]
一个递归就搞定了

  /// <summary>
        /// 绘制树
        /// </summary>
        /// <param name="p_TreeView">树控件 </param>
        /// <param name="p_DataTable">数据 </param>
        /// <param name="p_IdColumnIndex">主键INDEX </param>
        /// <param name="p_TextColumnIndex">文本的INDEX </param>
        /// <param name="p_ParentIdIndex">父键INDEX </param>
        /// <param name="p_ParentWhere">父节点条件 </param>
        public static void GetTree(TreeView p_TreeView, DataTable p_DataTable, int p_IdColumnIndex, int p_TextColumnIndex, int p_ParentIdIndex, string p_ParentWhere)
        {
            string _ParentName = p_DataTable.Columns[p_ParentIdIndex].ColumnName;
            DataRow[] _SubRow = p_DataTable.Select(_ParentName + "='" + p_ParentWhere + "'");
            for (int i = 0; i != _SubRow.Length; i++)
            {
                TreeNode _SubNode = new TreeNode();
                _SubNode.Text = _SubRow[i][p_TextColumnIndex].ToString();
                _SubNode.Tag = _SubRow[i][p_IdColumnIndex].ToString();
                p_TreeView.Nodes.Add(_SubNode);
                LoadNode(_SubNode, p_DataTable, _ParentName, p_IdColumnIndex, p_TextColumnIndex);
            }
        }

        private static void LoadNode(TreeNode p_Node, DataTable p_DataTable, string p_ParentName, int p_IdColumnIndex, int p_TextColumnIndex)
        {
            DataRow[] _SubRow = p_DataTable.Select(p_ParentName + "='" + p_Node.Tag.ToString() + "'");

            for (int i = 0; i != _SubRow.Length; i++)
            {
                TreeNode _SubNode = new TreeNode();
                _SubNode.Tag = _SubRow[i][p_IdColumnIndex].ToString();
                _SubNode.Text = _SubRow[i][p_TextColumnIndex].ToString();
                p_Node.Nodes.Add(_SubNode);
                LoadNode(_SubNode, p_DataTable, p_ParentName, p_IdColumnIndex, p_TextColumnIndex);
            }
        }
[/Quote]

能麻烦下给出完整的程序好么,谢谢~~
njlywy 2009-11-10
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 jack15850798154 的回复:]
在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,'北京',1)

insert tbtree (ID,Context,ParentID)  values ( 3,'天津',1)

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


下载Treeview控件地址
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


C#版本:

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
{
      /// <summary>
      /// WebForm1 的摘要说明
      /// </summary>
      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
      }
}
[/Quote]


程序报错,说:
else
{ //?添加当前节点的子节点
Node.Text = Row["ConText"].ToString();
pNode.Nodes.Add(Node);
Node.Expanded = true;
AddTree(Int32.Parse(Row["ID"].ToString()),Node); //再次递归
}
错误:“System.Web.UI.WebControls.TreeNode”并不包含“Nodes”的定义
错误指向pNode.Nodes.Add(Node);
解决下谢谢~~
zgke 2009-11-10
  • 打赏
  • 举报
回复
一个递归就搞定了

/// <summary>
/// 绘制树
/// </summary>
/// <param name="p_TreeView">树控件</param>
/// <param name="p_DataTable">数据</param>
/// <param name="p_IdColumnIndex">主键INDEX</param>
/// <param name="p_TextColumnIndex">文本的INDEX</param>
/// <param name="p_ParentIdIndex">父键INDEX</param>
/// <param name="p_ParentWhere">父节点条件</param>
public static void GetTree(TreeView p_TreeView, DataTable p_DataTable, int p_IdColumnIndex, int p_TextColumnIndex, int p_ParentIdIndex, string p_ParentWhere)
{
string _ParentName = p_DataTable.Columns[p_ParentIdIndex].ColumnName;
DataRow[] _SubRow = p_DataTable.Select(_ParentName + "='" + p_ParentWhere + "'");
for (int i = 0; i != _SubRow.Length; i++)
{
TreeNode _SubNode = new TreeNode();
_SubNode.Text = _SubRow[i][p_TextColumnIndex].ToString();
_SubNode.Tag = _SubRow[i][p_IdColumnIndex].ToString();
p_TreeView.Nodes.Add(_SubNode);
LoadNode(_SubNode, p_DataTable, _ParentName, p_IdColumnIndex, p_TextColumnIndex);
}
}

private static void LoadNode(TreeNode p_Node, DataTable p_DataTable, string p_ParentName, int p_IdColumnIndex, int p_TextColumnIndex)
{
DataRow[] _SubRow = p_DataTable.Select(p_ParentName + "='" + p_Node.Tag.ToString() + "'");

for (int i = 0; i != _SubRow.Length; i++)
{
TreeNode _SubNode = new TreeNode();
_SubNode.Tag = _SubRow[i][p_IdColumnIndex].ToString();
_SubNode.Text = _SubRow[i][p_TextColumnIndex].ToString();
p_Node.Nodes.Add(_SubNode);
LoadNode(_SubNode, p_DataTable, p_ParentName, p_IdColumnIndex, p_TextColumnIndex);
}
}
liujintaozyc 2009-11-10
  • 打赏
  • 举报
回复
就是一个递归查询
然后分别添加到treeview中

62,072

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧