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 System.Data.SqlClient;
using Microsoft.Web.UI.WebControls;
using MagicAjax;
namespace treeviewDemo
{
/// <summary>
/// createTree 的摘要说明。
/// </summary>
public class createTree : System.Web.UI.Page
{
protected Microsoft.Web.UI.WebControls.TreeView TreeView1;
protected SqlConnection myConn;
protected SqlDataAdapter myAdapter;
protected DataSet data;
protected MagicAjax.UI.Controls.AjaxPanel Ajaxpanel1;
protected System.Web.UI.WebControls.TextBox tbNode;
protected MagicAjax.UI.Controls.AjaxPanel panel1;
protected string query;
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["connString"];
myConn = new SqlConnection(ConnStr);
CreateDataSet();
InitTree(TreeView1.Nodes, "0");
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.TreeView1.SelectedIndexChange += new Microsoft.Web.UI.WebControls.SelectEventHandler(this.TreeView1_SelectedIndexChange);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
#region
// 将数据库的内容存入DataSet做缓冲
private DataSet CreateDataSet()
{
query = "SELECT * FROM TreeViewTable";
myAdapter = new SqlDataAdapter(query, myConn);
data = new DataSet();
myAdapter.Fill(data, "tree");
return data;
}
// 从DataSet中取数据建树
// 从根节点开始递归调用显示子树
private void InitTree(TreeNodeCollection Nds,string parentId)
{
TreeNode tmpNd;
DataRow [] rows = data.Tables[0].Select("ParentId='" + parentId + "'");
foreach(DataRow row in rows)
{
tmpNd = new TreeNode();
tmpNd.ID = row["NodeId"].ToString();
tmpNd.Text = row["NodeName"].ToString();
// tmpNd.NavigateUrl = row["Url"].ToString();
Nds.Add(tmpNd);
InitTree(tmpNd.Nodes, tmpNd.ID);
}
}
#endregion
private void TreeView1_SelectedIndexChange(object sender, Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs e)
{
TreeNode tn = TreeView1.GetNodeFromIndex(e.NewNode);
tbNode.Text = tn.Text;
} }
}
|