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的為根結點
三、執行後結果
*/