asp.net 2.0中treeview中动态增加结点

来源:互联网 发布:山东长川软件 编辑:程序博客网 时间:2024/05/17 02:52

   主要代码如下:

 

  1. <html>
  2. <head>
  3. </head> 
  4. <body> 
  5. <form id="form1" runat="server"
  6. <div> 
  7. <asp:TreeViewRunat="Server" ExpandImageUrl="Images/closed.gif" 
  8. CollapseImageUrl="Images/open.gif" 
  9. OnTreeNodePopulate="Node_Populate" ID="tvwauthors"
  10. <Nodes> 
  11. <asp:TreeNodeText="Authors" PopulateOnDemand=true 
  12. Value="0"/> 
  13. </Nodes> 
  14. </asp:TreeView> 
  15. </div> 
  16. </form> 
  17. </body> 
  18. </html> 

 后台代码:

  1. void Node_Populate(objectsender,System.Web.UI.WebControls.TreeNodeEventArgs e) 
  2. if(e.Node.ChildNodes.Count == 0) 
  3. switch( e.Node.Depth ) 
  4. case 0: 
  5. FillAuthors(e.Node); 
  6. break
  7. case 1: 
  8. FillTitlesForAuthors(e.Node); 
  9. break
  10. void FillAuthors(TreeNode node) 
  11. string connString = System.Configuration.ConfigurationSettings. 
  12. ConnectionStrings["NorthwindConnnection"].ConnectionString; 
  13. SqlConnection connection = new SqlConnection(connString); 
  14. SqlCommand command = new SqlCommand("Select * From 
  15. authors",connection); 
  16. SqlDataAdapter adapter = new SqlDataAdapter(command); 
  17. DataSet authors = new DataSet(); 
  18. adapter.Fill(authors); 
  19. if (authors.Tables.Count > 0) 
  20. foreach (DataRow row in authors.Tables[0].Rows) 
  21. TreeNode newNode = new 
  22. TreeNode(row["au_fname"].ToString() + " " + 
  23. row["au_lname"].ToString(), 
  24. row["au_id"].ToString()); 
  25. newNode.PopulateOnDemand = true//是否动态填充节点
  26. newNode.SelectAction = TreeNodeSelectAction.Expand; //选择节点时引发的事件(切换节点的展开和折叠状态。)
  27. node.ChildNodes.Add(newNode); 
  28. void FillTitlesForAuthors(TreeNode node) 
  29. string authorID = node.Value; 
  30. string connString = System.Configuration.ConfigurationSettings. 
  31. ConnectionStrings["NorthwindConnnection"].ConnectionString; 
  32. SqlConnection connection = new SqlConnection(connString); 
  33. SqlCommand command = new SqlCommand("Select T.title, 
  34. T.title_id From titles T" + 
  35. " Inner Join titleauthor TA on 
  36. T.title_id = TA.title_id " + 
  37. " Where TA.au_id = '" + authorID + "'", connection); 
  38. SqlDataAdapter adapter = new SqlDataAdapter(command); 
  39. DataSet titlesForAuthors = new DataSet(); 
  40. adapter.Fill(titlesForAuthors); 
  41. if (titlesForAuthors.Tables.Count > 0) 
  42. foreach (DataRow row in titlesForAuthors.Tables[0].Rows) 
  43. TreeNode newNode = new TreeNode( 
  44. row["title"].ToString(), row["title_id"].ToString()); 
  45. newNode.PopulateOnDemand = false//是否动态填充节点
  46. newNode.SelectAction = TreeNodeSelectAction.None; 
  47. node.ChildNodes.Add(newNode); 
原创粉丝点击