數據結構如下:
數據庫如下:
.ASPx文件如下:
<%@ Page language="c#" Codebehind="default.ASPx.cs" AutoEventWireup="false"
Inherits="treevIEw._default" %>
<%@ Register TagPrefix="IEwc" Namespace="Microsoft.Web.UI.WebControls"
Assembly="Microsoft.Web.UI.WebControls" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD Html 4.0 Transitional//EN" >
<Html>
<HEAD>
<title>default</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .Net 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClIEntScript" content="JavaScript">
<meta name="vs_targetSchema" content="' target=_blank>http://schemas.microsoft.com/intellisense/IE5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<iewc:TreeView id="TreeView1" runat="server"></iewc:TreeVIEw>
</form>
</body>
</Html>
CodeBehind代碼如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClIEnt;
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;
namespace treevIEw
{
/// <summary>
/// _default 的摘要說明。
/// </summary>
public class _default : System.Web.UI.Page
{
protected Microsoft.Web.UI.WebControls.TreeView TreeVIEw1;
DataSet myDS;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置用戶代碼以初始化頁面
CreateDataSet();
InitTree(TreeVIEw1.Nodes,"0");
}
private DataSet CreateDataSet()
{
SqlConnection myConnection = new SqlConnection(ConfigurationSettings.APPSettings["ConnectionString"]);
SqlDataAdapter myDA = new SqlDataAdapter("select * from TreeVIEw",myConnection);
myDS = new DataSet();
myDA.Fill(myDS,"tree");
return myDS;
}
private void InitTree(TreeNodeCollection Nds,string parentId)
{
DataView myDV = new DataVIEw();
TreeNode tmpNd;
string intId;
myDV.Table = myDS.Tables["tree"];
myDV.RowFilter="ParentId=" + parentId + "";
foreach(DataRowVIEw drv in myDV)
{
tmpNd = new TreeNode();
tmpNd.ID = drv["TreeId"].ToString();
tmpNd.Text = drv["TreeName"].ToString();
tmpNd.NavigateUrl = drv["URL"].ToString();
Nds.Add(tmpNd);
intId = drv["ParentId"].ToString();
InitTree(tmpNd.Nodes,tmpNd.ID);
}
}
#region Web 窗體設計器生成的代碼
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
}
}
頁面顯示(手工展開):
以上代碼通過驗證。