Microsoft KB Archive/319100

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

Article ID: 319100

Article Last Modified on 4/12/2007

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 1.0
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



This article was previously published under Q319100



For a Microsoft Visual C# .NET version of this article, see 317991.

IN THIS TASK
SUMMARY Requirements Create an ASP.NET Web Application by Using Visual Basic .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 Basic .NET
 Start Microsoft Visual Studio .NET. On the File menu, point to New, and then click Project. Click Visual Basic 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 ctrlGreeting As String = &quot;Welcome&quot; </li>  Add the following code to the code-behind file after the private variable declaration for ctrlGreeting: Public Property GreetingMessage As String Get GreetingMessage = ctrlGreeting End Get Set(ByVal Value As String) ctrlGreeting = Value End Set End Property 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 Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Greeting.Font.Bold = True 'Retrieves a cookie that contains the customer's name, 'assuming that it may have been set elsewhere in the application. Dim userName As HttpCookie = Request.Cookies(&quot;Name&quot;)

'See if the cookie exists. If (IsNothing(userName)) Then Greeting.Text = ctrlGreeting.ToString Else Greeting.Text = String.Format(&quot;{0} {1}&quot;, ctrlGreeting.ToString, userName.Value.ToString) End If End Sub </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;vb&quot; AutoEventWireup=&quot;false&quot; Codebehind=&quot;MenuCtrl.ascx.vb&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> 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 WithEvents MenuTable As System.Web.UI.WebControls.Table Protected WithEvents MyGreetingControl As NestedUserControls.GreetingCtrl 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 hyperlinks, add the following code to the code-behind class file to include a AddMenuItem method in the MenuCtrl: Private Sub AddMenuItem(ByVal linkName As String, ByVal linkURL As String) Dim menuRow As TableRow = New TableRow MenuTable.Rows.Add(menuRow) Dim menuCell As TableCell = New TableCell BuildLink(menuCell, linkName, linkURL) menuRow.Cells.Add(menuCell) End Sub

Private Sub BuildLink(ByVal menuCell As TableCell, ByVal linkCaption As String, ByVal linkHRef As String) Dim menuLink As HyperLink = New HyperLink menuLink.Text = linkCaption menuLink.NavigateUrl = linkHRef menuCell.Controls.Add(menuLink) End Sub 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 Property BackGroundColor As Color Get BackGroundColor = MenuTable.BackColor End Get Set(ByVal Value As Color) MenuTable.BackColor = Value End Set End Property </li> <li> Replace the existing code in the Page_Load event handler for the MenuCtrl with the following code: Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Adding a cookie for demonstration only. 'This is typically set in another section of the application, 'such as when you collect logon information. Dim userName As HttpCookie = New HttpCookie(&quot;Name&quot;, &quot;Joe&quot;) Response.Cookies.Add(userName)

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

MyGreetingControl.GreetingMessage = &quot;Howdy&quot; End Sub 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;vb&quot; AutoEventWireup=&quot;false&quot; Codebehind=&quot;SamplePage.aspx.vb&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:

Name ' ' is not declared.

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