標籤:track obj hid == 產品 new t article cts 導致
1.TreeNode的PopulateOnDemand="True"後節點就是動態從後台載入的.
2.但是如果上層TreeView的EnableClientScript="false",就會導致頁面Postback
3.TreeView的TreeNodePopulate是PopulateOnDemand="True"並且TreeNode內已有資料才觸發的
4.TreeNode的Depth屬性是指從根結點算起到現在節點的層數,根結點層數為0
5.TreeNode NewNode = new TreeNode(row["CategoryName"].ToString(),row["CategoryID"].ToString())的第一個參數設定了
TreeNode類的Value 屬性值.這個屬性值會在發生TreeNodePopulate()事件的TreeNode對像回傳用到.sqlQuery.Parameters.Add
("@categoryid", SqlDbType.Int).Value =node.Value;
附代碼:
一、HTML
- <asp:SqlDataSource ID="SqlDataSource1" runat="server"
- ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
- SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]">
- </asp:SqlDataSource>
- <asp:TreeView ID="TreeView1" runat="server" MaxDataBindDepth="2"
- ontreenodepopulate="TreeView1_TreeNodePopulate" EnableClientScript="true" ExpandDepth="0">
- <Nodes>
- <asp:TreeNode PopulateOnDemand="True" Text="產品列表" Value="產品列表"></asp:TreeNode>
- </Nodes>
- </asp:TreeView>
二、C#
- protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
- {
- if (e.Node.ChildNodes.Count == 0)
- {
- switch (e.Node.Depth)
- {
- case 0:
- PopulateCategories(e.Node);
- break;
- case 1:
- PopulateProducts(e.Node);
- break;
- }
- }
- }
- void PopulateCategories(TreeNode node)
- {
- SqlCommand sqlQuery = new SqlCommand(
- "Select CategoryName, CategoryID From Categories");
- DataSet resultSet;
- resultSet = RunQuery(sqlQuery);
- if (resultSet.Tables.Count > 0)
- {
- foreach (DataRow row in resultSet.Tables[0].Rows)
- {
- TreeNode NewNode = new
- TreeNode(row["CategoryName"].ToString(),
- row["CategoryID"].ToString());
- NewNode.PopulateOnDemand = true;
- NewNode.SelectAction = TreeNodeSelectAction.Expand;
- node.ChildNodes.Add(NewNode);
- }
- }
- }
- void PopulateProducts(TreeNode node)
- {
- SqlCommand sqlQuery = new SqlCommand();
- sqlQuery.CommandText = "Select ProductName From Products " +
- " Where CategoryID = @categoryid";
- sqlQuery.Parameters.Add("@categoryid", SqlDbType.Int).Value =
- node.Value;
- DataSet ResultSet = RunQuery(sqlQuery);
- if (ResultSet.Tables.Count > 0)
- {
- foreach (DataRow row in ResultSet.Tables[0].Rows)
- {
- TreeNode NewNode = new
- TreeNode(row["ProductName"].ToString());
- NewNode.PopulateOnDemand = false;
- NewNode.SelectAction = TreeNodeSelectAction.None;
- node.ChildNodes.Add(NewNode);
- }
- }
- }
- private DataSet RunQuery(SqlCommand sqlQuery)
- {
- string connectionString =
- ConfigurationManager.ConnectionStrings
- ["NorthwindConnectionString"].ConnectionString;
- SqlConnection DBConnection =
- new SqlConnection(connectionString);
- SqlDataAdapter dbAdapter = new SqlDataAdapter();
- dbAdapter.SelectCommand = sqlQuery;
- sqlQuery.Connection = DBConnection;
- DataSet resultsDataSet = new DataSet();
- try
- {
- dbAdapter.Fill(resultsDataSet);
- }
- catch
- {
- labelStatus.Text = "Unable to connect to SQL Server.";
- }
- return resultsDataSet;
- }
Asp.net TreeView動態載入節點(一)