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;
- }
时间: 2024-10-19 05:28:52