主要代码如下:
- <html>
- <head>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:TreeViewRunat="Server" ExpandImageUrl="Images/closed.gif"
- CollapseImageUrl="Images/open.gif"
- OnTreeNodePopulate="Node_Populate" ID="tvwauthors">
- <Nodes>
- <asp:TreeNodeText="Authors" PopulateOnDemand=true
- Value="0"/>
- </Nodes>
- </asp:TreeView>
- </div>
- </form>
- </body>
- </html>
后台代码:
- void Node_Populate(objectsender,System.Web.UI.WebControls.TreeNodeEventArgs e)
- {
- if(e.Node.ChildNodes.Count == 0)
- {
- switch( e.Node.Depth )
- {
- case 0:
- FillAuthors(e.Node);
- break;
- case 1:
- FillTitlesForAuthors(e.Node);
- break;
- }
- }
- }
- void FillAuthors(TreeNode node)
- {
- string connString = System.Configuration.ConfigurationSettings.
- ConnectionStrings["NorthwindConnnection"].ConnectionString;
- SqlConnection connection = new SqlConnection(connString);
- SqlCommand command = new SqlCommand("Select * From
- authors",connection);
- SqlDataAdapter adapter = new SqlDataAdapter(command);
- DataSet authors = new DataSet();
- adapter.Fill(authors);
- if (authors.Tables.Count > 0)
- {
- foreach (DataRow row in authors.Tables[0].Rows)
- {
- TreeNode newNode = new
- TreeNode(row["au_fname"].ToString() + " " +
- row["au_lname"].ToString(),
- row["au_id"].ToString());
- newNode.PopulateOnDemand = true; //是否动态填充节点
- newNode.SelectAction = TreeNodeSelectAction.Expand; //选择节点时引发的事件(切换节点的展开和折叠状态。)
- node.ChildNodes.Add(newNode);
- }
- }
- }
- void FillTitlesForAuthors(TreeNode node)
- {
- string authorID = node.Value;
- string connString = System.Configuration.ConfigurationSettings.
- ConnectionStrings["NorthwindConnnection"].ConnectionString;
- SqlConnection connection = new SqlConnection(connString);
- SqlCommand command = new SqlCommand("Select T.title,
- T.title_id From titles T" +
- " Inner Join titleauthor TA on
- T.title_id = TA.title_id " +
- " Where TA.au_id = '" + authorID + "'", connection);
- SqlDataAdapter adapter = new SqlDataAdapter(command);
- DataSet titlesForAuthors = new DataSet();
- adapter.Fill(titlesForAuthors);
- if (titlesForAuthors.Tables.Count > 0)
- {
- foreach (DataRow row in titlesForAuthors.Tables[0].Rows)
- {
- TreeNode newNode = new TreeNode(
- row["title"].ToString(), row["title_id"].ToString());
- newNode.PopulateOnDemand = false; //是否动态填充节点
- newNode.SelectAction = TreeNodeSelectAction.None;
- node.ChildNodes.Add(newNode);
- }
- }
- }