ASP.NET 2.0 树型数据的显示源代码(递归)

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{

SqlConnection conn = new SqlConnection("workstation id="cyz";user id=sa;password=****;initial catalog=pubs;persist security info=false");
DataSet ds = new DataSet();

protected void Page_Load(object sender, EventArgs e)
{
if (! (IsPostBack) )
{
SqlDataAdapter da = new SqlDataAdapter("select * from t_tree order by parentid", conn);
da.Fill(ds, "t_tree");
InitTree0();

}
}
private void InitTree0() //根结点加载函数
{
TV.Nodes.Clear(); //TV为TreeView控件
DataRow[] rows = ds.Tables["t_tree"].Select("parentid=0");
for (int i = 0; i < rows.Length; i++)
{
TreeNode T_root = new TreeNode();
DataRow dr = rows[i];
T_root.Text = dr["Descricpt"].ToString();
TV.Nodes.Add(T_root);
InitTree(T_root, dr["id"].ToString());//根结点加载完后,开始调用加载子结点的函数,并开始递归。
}
}
private void InitTree(TreeNode Nd,String Parent_id) //子树结点加载函数
{
DataRow[] rows = ds.Tables["t_tree"].Select("parentid="+Parent_id );
if (rows != null)
{
for (int i = 0; i < rows.Length;i++ )
{
TreeNode Tnd = new TreeNode();
DataRow dr=rows[i];
Tnd.Text = dr["Descricpt"].ToString();
Nd.ChildNodes.Add(Tnd);
InitTree(Tnd,dr["id"].ToString());//递归调用
}
}
}
}


/*后注:
一、T_Tree表生成脚本
CREATE TABLE [dbo].[T_Tree] (
[ID] [int] NOT NULL ,
[ParentID] [int] NOT NULL ,
[Descricpt] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
二、T_Tree表数据

Parentid=0的为根结点
三、执行后结果


你可能感兴趣的:(asp.net)