using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Microsoft.Web.UI.WebControls;
namespace Example
{
	public class TreeViewExample6 : System.Web.UI.Page
	{
		protected SqlConnection myConn;
		protected SqlDataAdapter myAdapter;
		protected DataSet data;
		protected Microsoft.Web.UI.WebControls.TreeView myTree;
		protected string query;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// 从Web.config配置节中读取数据库连接字符串
			string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
			myConn = new SqlConnection(ConnStr);
			CreateDataSet();
			InitTree(myTree.Nodes, "0");
		}

		// 将数据库的内容存入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);
			}
		}

		#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
	}
}
