How to implement nested Web user controls in ASP.NET by using Visual C# .NET

Article translations Article translations
Article ID: 317991 - View products that this article applies to.
This article was previously published under Q317991
Expand all | Collapse all

On This Page

SUMMARY

This step-by-step article demonstrates how to implement nested Web user controls in an ASP.NET application. The concepts are basically the same as when you create Web user controls to include in an .aspx page or in another Web user control, which is typically referred to as nesting.

One of the main reasons to use nested Web user controls is make it easier to reuse code. By breaking up functionality into separate user controls, your user control development can benefit from reusing the same code and, therefore, the same user control interface, which adds value to your .aspx pages.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
  • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows XP Professional
  • Microsoft .NET Framework
  • Microsoft Visual Studio .NET
  • Microsoft Internet Information Services (IIS)

Create an ASP.NET Web Application by Using Visual C# .NET

  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.
  4. In the Location box, replace the WebApplication# default name with NestedUserControls in the URL path. If you are using the local server, you can leave the server name as http://localhost. The path appears as follows in the Location box:
    http://localhost/NestedUserControls

Create the User Controls

In the next two sections, you create an example of a simple Web user control that retrieves and displays a user's name from a cookie. This control will then be nested in another Web user control (MenuCtrl.ascx).

Build the Greeting Control

  1. Follow these steps to add a new Web user control that is named GreetingCtrl.ascx:
    1. In Solution Explorer, right-click the project node, point to Add, and then click Add Web User Control.
    2. In the Name box, type GreetingCtrl.ascx.
  2. Switch to Design view in the editor, and then drag a Web Forms Label control from the toolbox to the page.
  3. In the Properties window, change the ID property of the Label control to Greeting, and then clear the value of the Text property.
  4. Right-click the page, and then click View Code.
  5. Add the following private variable declaration to the code-behind file in the GreetingCtrl class:
    private string ctrlGreeting = "Welcome";
    					
  6. Add the following code to the code-behind file after the private variable declaration for ctrlGreeting:
    public string GreetingMessage
    {
    	set{ctrlGreeting = value;}
    	get{return ctrlGreeting;}
    } 
    						
    This code adds a property that is named GreetingMessage. GreetingMessage uses a get block (accessor) and a set block (mutator) to retrieve values and to assign values for the ctrlGreeting variable.
  7. Replace the existing code in the Page_Load event handler with the following code:
    private void Page_Load(object sender, System.EventArgs e)
    {
             Greeting.Font.Bold = true;
    	//Retrieves a cookie that contains the customer's name,
    	//assuming that it may have been set elsewhere in the application.
    	HttpCookie userName = Request.Cookies["Name"];
    			
    	//See if the cookie exists.
    	if(userName.Value == null)
    	{
    		Greeting.Text = ctrlGreeting.ToString();
    	}
    	else
    	{
    		Greeting.Text = string.Format("{0} {1}",ctrlGreeting.ToString(),userName.Value.ToString());
    	} 
    }
    					

Build the Menu Control

  1. Follow these steps to add a new Web user control that is named MenuCtrl.ascx:
    1. In Solution Explorer, right-click the project node, point to Add, and then click Add Web User Control.
    2. In the Name box, type MenuCtrl.ascx.
  2. Switch to HTML view in the editor, and then add the following code:
    <%@ Control Language="c#" AutoEventWireup="false" Codebehind="MenuCtrl.ascx.cs" Inherits="NestedUserControls.MenuCtrl" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
    <%@ Register TagPrefix="uc1" TagName="GreetingCtrl" Src="GreetingCtrl.ascx" %>
    <asp:Table  ID=MenuTable Runat=server>
    <asp:TableRow>
    	<asp:TableCell HorizontalAlign="Center">
    		<uc1:GreetingCtrl id="MyGreetingControl" runat="server"></uc1:GreetingCtrl>
    	</asp:TableCell>
    </asp:TableRow>
    </asp:Table>
    						
    By default, Visual Studio .NET adds the code for the @ Control directive and the @ Register directive of the GreetingCtrl. The @ Register directive is used to include user controls in Web Form pages and other user controls.

    Additionally, notice that the @ Register directive includes the TagPrefix, the TagName, and the Src attributes.

    • The TagPrefix attribute determines a unique namespace for the user control. This differentiates between multiple user controls with the same name.
    • The TagName attribute is the unique name that you select for the user control.
    • The Src attribute is the virtual path to the user control.
    NOTE: After you register a Web user control, you can place the @ Control directive in a Web Forms page just as you would an ordinary server control by including the following attribute:
    runat="server"
    					
  3. Right-click the page, and then click View Code.
  4. To declare the GreetingCtrl so that it is referenced in the code-behind class file and to list the Web Forms Table control (MenuTable), add the following code to the code-behind class file:
    protected NestedUserControls.GreetingCtrl MyGreetingControl;
    protected System.Web.UI.WebControls.Table MenuTable;
    						
    NOTE: When you are in Design view in Visual Studio .NET, you can drag a user control from Solution Explorer onto another user control or onto an .aspx page. This automatically lists the control with the @ Register directive. However, you must still declare an instance of the user control in the code-behind class file to reference it properly. For more information, see the Troubleshooting section of this article.
  5. To programmatically specify menu links, add the following code to the code-behind class file to include a AddMenuItem method in the MenuCtrl:
    private void AddMenuItem(string linkName,string linkURL)
    {
    	TableRow menuRow = new TableRow();
    	MenuTable.Rows.Add(menuRow);
    	TableCell menuCell = new TableCell();
    	BuildLink(menuCell, linkName, linkURL);	
    	menuRow.Cells.Add(menuCell);
    }
    
    private void BuildLink(TableCell menuCell, string linkCaption, string linkHRef) 
    {
    	HyperLink menuLink = new HyperLink();
    	menuLink.Text = linkCaption;
    	menuLink.NavigateUrl = linkHRef;
    	menuCell.Controls.Add(menuLink);
    }
    						
    Notice that this code adds the BuildLink method, which the AddMenuItem method calls to build the hyperlinks for your menu. You can make the AddItem method public to expose AddItem. By exposing AddItem, you can set the menu hyperlink items from any user control or .aspx page to which the control is added.

    In this example, you set the menu hyperlink values in the control itself, expecting that the control will be used with the same hyperlinks throughout the application. By using this method, you can modify the control and make sure that the changes are applied automatically to all of the pages or to other user controls that use the control.

    If you want to make AddItem public and call AddItem from an .aspx page, you must modify the code in every .aspx page that implements AddItem if the hyperlinks were to change. This may be useful if you want MenuCtrl to be more generic and if you have to set the hyperlinks based on the page or on other user control to which the control is added. This depends on what role the control will serve and how you want to implement it.
  6. Add the following code to the code-behind class file to create a property named BackGroundColor that allows you to set the background color of the control by using the BackColor property of the Web Forms Table control (MenuTable):
    public Color BackGroundColor
    {
    	set{MenuTable.BackColor = value;}
    	get{return MenuTable.BackColor;}
    }
    					
  7. Replace the existing code in the Page_Load event handler for the MenuCtrl with the following code:
    private void Page_Load(object sender, System.EventArgs e)
    		{
    			//Adding a cookie for demonstration only.
    			//This is typically set in another section of the application, 
    			//such as when you collect logon information.
    			HttpCookie userName = new HttpCookie("Name", "Joe");
    			Response.Cookies.Add(userName);
    
    			this.AddMenuItem("MSN", "http://www.MSN.com");
    			this.AddMenuItem("Microsoft", "http://www.microsoft.com");
    			this.AddMenuItem(".NET Development Center","http://msdn.microsoft.com/netframework/default.aspx");
    
    			MyGreetingControl.GreetingMessage = "Howdy";
    		}
    						
    This code sets the GreetingMessage property of the GreetingCtrl control to "Howdy." Additionally, this code builds the hyperlinks for the MenuCtrl control.

Add the User Control to a Web Form

In this section, you add the MenuCtrl control that contains the nested GreetingCtrl to a Web Forms page that is named SamplePage.aspx.
  1. Follow these steps to add a new ASP.NET Web Form that is named SamplePage.aspx to the project:
    1. In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.
    2. In the Name box, type SamplePage.aspx.
  2. Switch to HTML view in the editor, and then add the following code:
    <%@ Page language="c#" Codebehind="SamplePage.aspx.cs" AutoEventWireup="false" Inherits="NestedUserControls.SamplePage" %>
    <%@ Register TagPrefix="uc1" TagName="MenuCtrl" Src="MenuCtrl.ascx" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    	<title>SamplePage</title>
    </HEAD>
    <body>
    	<form id="SamplePage" method="post" runat="server">
    	<TABLE WIDTH="150" BORDER="1" align=left>
    		<TR>
    			<TD><uc1:menuctrl id="Menu" runat="server" BackGroundColor="#99ccff"></uc1:menuctrl></TD>
    		</TR>
    	</TABLE>		
    	</form>
    </body>
    </HTML>
    						
    By default, Visual Studio .NET adds the @ Page directive for you.
  3. On the File menu, click Save All to save the Web Form and other files that are associated with the project.
  4. On the Build menu in the Visual Studio .NET integrated development environment (IDE), click Build Solution to build the project.
  5. In Solution Explorer, right-click SamplePage.aspx, and then click View in Browser. Notice how the GreetingCtrl and the MenuCtrl controls are rendered in the browser. Notice that both controls retain their functionality and appear to be another part of the Web page.

Troubleshooting

If you do not specifically declare a user control in the code-behind class file, and if you then try to reference the user control in your code, you may receive a build error that is similar to the following error message:
The type or namespace name 'User Control Name' could not be found (are you missing a using directive or an assembly reference?)
You must specifically declare user controls when you program against them in the code-behind class file.

For additional information, click the article number below to view the article in the Microsoft Knowledge Base:
316370 BUG: Visual Studio .NET Does Not Generate a Code-Behind Declaration for Web User Controls

REFERENCES

For additional information about ASP.NET development resources, click the article number below to view the article in the Microsoft Knowledge Base:
305140 INFO: ASP.NET Roadmap
For more information about how to use ASP.NET Web user controls, visit the following MSDN Web sites:
Web Forms User Controls
http://msdn.microsoft.com/en-us/library/aa735701.aspx

Converting a Web Forms Page to a User Control
http://msdn.microsoft.com/en-us/library/aa719784.aspx

Handling User Control Events
http://msdn.microsoft.com/en-us/library/t4z863dh.aspx

Properties

Article ID: 317991 - Last Review: April 14, 2006 - Revision: 4.6
APPLIES TO
  • Microsoft ASP.NET 1.1
  • Microsoft ASP.NET 1.0
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbctrlcreate kbhowtomaster KB317991

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com