Microsoft KB Archive/317991

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

Article ID: 317991

Article Last Modified on 4/14/2006

-

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

-



This article was previously published under Q317991





For a Microsoft Visual Basic .NET version of this article, see 319100.

IN THIS TASK
SUMMARY Requirements Create an ASP.NET Web Application by Using Visual C# .NET Create the User Controls
 * Build the Greeting Control
 * Build the Menu Control

Add the User Control to a Web Form Troubleshooting REFERENCES



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.

back to the top

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)

back to the top

Create an ASP.NET Web Application by Using Visual C# .NET
 Start Microsoft Visual Studio .NET. On the File menu, point to New, and then click Project. Click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates. 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



back to the top

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).

back to the top

Build the Greeting Control
 Follow these steps to add a new Web user control that is named GreetingCtrl.ascx:  In Solution Explorer, right-click the project node, point to Add, and then click Add Web User Control.</li> In the Name box, type GreetingCtrl.ascx .</li></ol> </li> Switch to Design view in the editor, and then drag a Web Forms Label control from the toolbox to the page.</li> In the Properties window, change the ID property of the Label control to Greeting, and then clear the value of the Text property.</li> Right-click the page, and then click View Code.</li>  Add the following private variable declaration to the code-behind file in the GreetingCtrl class: private string ctrlGreeting = &quot;Welcome&quot;; </li>  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. </li>  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[&quot;Name&quot;]; //See if the cookie exists. if(userName.Value == null) {       Greeting.Text = ctrlGreeting.ToString; }   else {       Greeting.Text = string.Format(&quot;{0} {1}&quot;,ctrlGreeting.ToString,userName.Value.ToString); } }                   </li></ol>

back to the top

Build the Menu Control
 Follow these steps to add a new Web user control that is named MenuCtrl.ascx:  In Solution Explorer, right-click the project node, point to Add, and then click Add Web User Control.</li> In the Name box, type MenuCtrl.ascx .</li></ol> </li>  Switch to HTML view in the editor, and then add the following code: <%@ Control Language=&quot;c#&quot; AutoEventWireup=&quot;false&quot; Codebehind=&quot;MenuCtrl.ascx.cs&quot; Inherits=&quot;NestedUserControls.MenuCtrl&quot; TargetSchema=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;%> <%@ Register TagPrefix=&quot;uc1&quot; TagName=&quot;GreetingCtrl&quot; Src=&quot;GreetingCtrl.ascx&quot; %> <asp:Table ID=MenuTable Runat=server> <asp:TableRow> <asp:TableCell HorizontalAlign=&quot;Center&quot;> <uc1:GreetingCtrl id=&quot;MyGreetingControl&quot; runat=&quot;server&quot;></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.

<ul> The TagPrefix attribute determines a unique namespace for the user control. This differentiates between multiple user controls with the same name.</li> <li>The TagName attribute is the unique name that you select for the user control.</li> <li>The Src attribute is the virtual path to the user control.</li></ul>

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=&quot;server&quot; </li> <li>Right-click the page, and then click View Code.</li> <li> 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. </li> <li> 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. </li> <li> 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;} }                   </li> <li> 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(&quot;Name&quot;, &quot;Joe&quot;); Response.Cookies.Add(userName);

this.AddMenuItem(&quot;MSN&quot;, &quot;http://www.MSN.com&quot;); this.AddMenuItem(&quot;Microsoft&quot;, &quot;http://www.microsoft.com&quot;); this.AddMenuItem(&quot;.NET Development Center&quot;,&quot;http://msdn.microsoft.com/netframework/default.aspx&quot;);

MyGreetingControl.GreetingMessage = &quot;Howdy&quot;; } This code sets the GreetingMessage property of the GreetingCtrl control to &quot;Howdy.&quot; Additionally, this code builds the hyperlinks for the MenuCtrl control. </li></ol>

back to the top

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. <ol> <li>Follow these steps to add a new ASP.NET Web Form that is named SamplePage.aspx to the project: <ol style="list-style-type: lower-alpha;"> <li>In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.</li> <li>In the Name box, type SamplePage.aspx .</li></ol> </li> <li> Switch to HTML view in the editor, and then add the following code: <%@ Page language=&quot;c#&quot; Codebehind=&quot;SamplePage.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;NestedUserControls.SamplePage&quot; %> <%@ Register TagPrefix=&quot;uc1&quot; TagName=&quot;MenuCtrl&quot; Src=&quot;MenuCtrl.ascx&quot; %> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; > <HTML> <HEAD> SamplePage </HEAD> <form id=&quot;SamplePage&quot; method=&quot;post&quot; runat=&quot;server&quot;> </HTML> By default, Visual Studio .NET adds the @ Page directive for you. </li> <li>On the File menu, click Save All to save the Web Form and other files that are associated with the project.</li> <li>On the Build menu in the Visual Studio .NET integrated development environment (IDE), click Build Solution to build the project.</li> <li>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.</li></ol>

back to the top

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 ' ' 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

back to the top

<div class="references_section">