Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How to dynamically add nodes to a TreeView WebBrowser control by using Visual C# .NET


View products that this article applies to.

Summary

This step-by-step article demonstrates how to add multiple levels of nodes to a Microsoft Internet Explorer TreeView WebControl by using a DataSet object that includes multiple tables.

This article also demonstrates three ways to optimize how much data you send and when you send the data to the client. For a small set of data, you want to send all of the data immediately. For a larger set of data, you may want to send only the root level nodes and then add only child nodes that are requested. For even larger sets of data, you may want to remove child nodes that are no longer needed.

Download Internet Explorer WebControls

You must download the Internet Explorer WebControls to your development computer before you can use the TreeView WebControl in a Web application. To download the Internet Explorer WebControls, visit the following Microsoft Web site:

Add the TreeView WebControl to the Visual Studio .NET toolbox

To add the TreeView WebControl to the Microsoft Visual Studio .NET toolbox, follow these steps:
  1. Start Microsoft Visual Studio .NET.
  2. On the View menu, click Toolbox.
  3. Right-click the Web Forms tab in the toolbox, and then click Customize Toolbox.

    In Visual Studio .NET 2003:
    Right-click the Web Forms tab in the toolbox, and then click Add/Remove items.
  4. Click the .NET Framework Components tab. Notice that this tab lists at least two TreeView entries. One TreeView entry is for Windows applications such as .exe files. Another TreeView entry is the Internet Explorer TreeView WebControl.
  5. View the Namespace column to identify the TreeView WebControl with the Microsoft.Web.UI.WebControls namespace. Click to select the check box for this TreeView WebControl, and then click OK.

Create the Visual C# .NET project and add the TreeView WebControl

  1. Start Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects under Project Types, click ASP.NET Web Application under Templates, and then click OK.
  4. On the Project menu, click Add Web Form.
  5. In the Name box, type a name for the Web Form, and then click Open.
  6. Follow these steps to add a TreeView WebControl to the Web Form:
    1. On the View menu, click Toolbox.
    2. Click the Web Forms tab.
    3. Locate the TreeView WebControl. You may have to scroll through the list to locate the TreeView control.
    4. Drag the TreeView WebControl from the toolbox to your Web Form. By default, the control is named TreeView1.
  7. Click TreeView1 on the Web Form, and then press F4 to see the Properties window.
  8. Locate the AutoPostBack property in the Properties window. Set this property according to the following guidelines:
    • Set AutoPostBack to True if you are not sending all of the data immediately (for example, if you are sending only the root nodes and particular child nodes). This option posts to the server every time the user changes the selection, expands a node, or collapses a node.
    • Set AutoPostBack to False if you are sending all of the data immediately (for example, for the sample in the Send all data immediately section). With this option, most activity remains on the client.

Add code to send data

Send all data immediately

  1. Press F7 to open the code-behind window for the page.
  2. Add the following code to the top of the code-behind window, before namespace:
    using System.Data.SqlClient;
    using Microsoft.Web.UI.WebControls;
  3. Replace the code in the Page_Load event with the following code:
    private void Page_Load(object sender, System.EventArgs e)
    {
        if (!Page.IsPostBack)
        {
    
    	// You may have to change the ConnectionString to 
    	// access the Pubs database on your server.
    	string strConnectionString   = "data source=(local);" +
    			"initial catalog=pubs;integrated security=SSPI";
    	string strSQLAuthors = "SELECT authors.au_id," +
    			"authors.au_lname, authors.au_fname FROM " +
    			"authors ORDER BY authors.au_lname, " +
    			"authors.au_fname, authors.au_id";
    	string strSQLTitles = "SELECT titleauthor.au_id, " +
    		"titles.title FROM titleauthor INNER JOIN titles " +
    		"ON titleauthor.title_id = titles.title_id " +
    		"ORDER BY titles.title";
    		
    	TreeNode nodeAuthor;
    	TreeNode nodeTitle;
    	SqlConnection cnn;
    	SqlDataAdapter cmAuthors;
    	SqlDataAdapter cmTitles;
    	DataSet ds;
    				    
    	//Create the Connection and the DataSet object, and then open the connection.
    	cnn = new  SqlConnection(strConnectionString);
    	ds = new DataSet();
    	cnn.Open();
    	
    	//Add an Authors table to the DataSet.
    	cmAuthors = new SqlDataAdapter(strSQLAuthors, cnn);
    	cmAuthors.Fill(ds, "Authors");
    
    	//Add a Titles table to the DataSet.
    	cmTitles = new SqlDataAdapter(strSQLTitles, cnn);
    	cmTitles.Fill(ds, "Titles");
    		
    	//Create a relation between the Authors and the Titles tables.
    	ds.Relations.Add("AuthorTitle", 
    			ds.Tables["Authors"].Columns["au_id"], 
    			ds.Tables["Titles"].Columns["au_id"]);
    
    	//Populate the TreeView from the DataSet.
    	foreach (DataRow rowAuthor in ds.Tables["Authors"].Rows)
    	{
    		nodeAuthor = new TreeNode();
    		nodeAuthor.Text = rowAuthor["au_lname"] + ", " 
    				+ rowAuthor["au_fname"];
    		TreeView1.Nodes.Add(nodeAuthor);
    		foreach (DataRow rowTitle in
                                     rowAuthor.GetChildRows("AuthorTitle"))
    		{
    			nodeTitle = new TreeNode();
    			nodeTitle.Text = rowTitle["Title"].ToString();
    			nodeAuthor.Nodes.Add(nodeTitle);
    		}
    	}
    
    	//Clean up.
    	ds.Dispose();
    	cmAuthors.Dispose();
    	cmTitles.Dispose();
    	cnn.Close();
    	cnn.Dispose();
        }
    }

Send only root nodes and requested child nodes

  1. Press F7 to open the code-behind window for the page.
  2. Add the following code to the top of the code-behind window, before namespace:
    using System.Data.SqlClient;
    using Microsoft.Web.UI.WebControls;
  3. Replace the code in the Page_Load event with the following two procedures:
    private void Page_Load(object sender, System.EventArgs e)
    {
    	if (!Page.IsPostBack)
    	{
             	//You may have to change the ConnectionString to access the
    	        //Pubs database on your server.
    		string strConnectionString   = "data source=(local);" +
    			"initial catalog=pubs;integrated security=SSPI";
    		string strSQLAuthors = "SELECT authors.au_id," +
    			"authors.au_lname, authors.au_fname FROM " +
    			"authors ORDER BY authors.au_lname, " +
    			"authors.au_fname, authors.au_id";
    		TreeNode nodeAuthor;
    		SqlConnection cnn;
    		SqlDataAdapter cmAuthors;
    		DataSet ds;
        
    		//Create the Connection and the DataSet, and then open the connection.
    		cnn = new SqlConnection(strConnectionString);
    		ds = new DataSet();
    		cnn.Open();
    
    		//Add an Authors table to the DataSet.
    		cmAuthors = new SqlDataAdapter(strSQLAuthors, cnn);
    		cmAuthors.Fill(ds, "Authors");
    
    		//Populate the TreeView from the DataSet.
    		foreach (DataRow rowAuthor in ds.Tables["Authors"].Rows)
    		{
    			nodeAuthor = new TreeNode();
    			nodeAuthor.Text = rowAuthor["au_lname"] + ", " 
    				+ rowAuthor["au_fname"];
    			nodeAuthor.NodeData = rowAuthor["au_id"].ToString();
    			nodeAuthor.Expandable = ExpandableValue.CheckOnce;
    			TreeView1.Nodes.Add(nodeAuthor);
    		}
    
    		//Clean up.
    		ds.Dispose();
    		cmAuthors.Dispose();
    		cnn.Close();
    		cnn.Dispose();
    	}
    }
    private void TreeView1_Expand( object sender ,  Microsoft.Web.UI.WebControls.TreeViewClickEventArgs e)
    {
    	string strConnectionString   = "data source=(local);" +
    		"initial catalog=pubs;integrated security=SSPI";
    	string strSQLTitles; 
    	SqlConnection cnn; 
    	SqlDataAdapter cmTitles; 
    	DataSet ds;
    	TreeNode nodeTitle;
    	TreeNode nodeAuthor;
    	
            nodeAuthor = ((Microsoft.Web.UI.WebControls.TreeView)sender).Nodes[(int.Parse(e.Node))];
    	if (nodeAuthor.Nodes.Count == 0) 
    	{
    		//Create the Connection and the DataSet, and then open the connection.
    		cnn = new SqlConnection(strConnectionString);
    		ds = new DataSet();
    		cnn.Open();
    
    		//Add a Titles table to the DataSet.
    		strSQLTitles = "SELECT titles.title FROM titles " +
    			"INNER JOIN titleauthor ON titles.title_id " +
    			"= titleauthor.title_id where titleauthor.au_id " +
    			"= '" + nodeAuthor.NodeData.ToString() +
    			"' ORDER BY titles.title";
    		cmTitles = new SqlDataAdapter(strSQLTitles, cnn);
    		cmTitles.Fill(ds, "Titles");
    
    		foreach (DataRow rowTitle in ds.Tables["Titles"].Rows)
    		{
    			nodeTitle = new TreeNode();
    			nodeTitle.Text = rowTitle["Title"].ToString();
    			nodeAuthor.Nodes.Add(nodeTitle);
    		}
    
    		//Clean up.
    		ds.Dispose();
    		cmTitles.Dispose();
    		cnn.Close();
    		cnn.Dispose();
    	}
    	
    }
  4. Add the following code to the OnInit procedure:
    TreeView1.Expand += new ClickEventHandler(this.TreeView1_Expand);

Send only root nodes and minimum child nodes

  1. Complete the steps in the Send only root nodes and requested child nodes section.
  2. Add one more procedure to the code:
    private void TreeView1_Collapse(object sender  , Microsoft.Web.UI.WebControls.TreeViewClickEventArgs e ) 
    {
    	
    	TreeNode nodeAuthor; 
    	nodeAuthor = ((Microsoft.Web.UI.WebControls.TreeView)sender).Nodes[(int.Parse(e.Node))];
    	if (nodeAuthor.Nodes.Count > 0)
    	{
    		nodeAuthor.Nodes.Clear();
    		nodeAuthor.Expandable = ExpandableValue.Always;
    	}
    }
  3. Add the following code to the OnInit procedure:
    TreeView1.Collapse +=new ClickEventHandler(this.TreeView1_Collapse);

↑ Back to the top


References

For more information, click the following article number to view the article in the Microsoft Knowledge Base:
306154 How to display hierarchical data by using nested repeater controls and Visual C# .NET
For more information, visit the following MSDN Web sites:

↑ Back to the top


Keywords: KB320909, kbservercontrols, kbhowtomaster

↑ Back to the top

Article Info
Article ID : 320909
Revision : 12
Created on : 4/21/2006
Published on : 4/21/2006
Exists online : False
Views : 544