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
- 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
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
- 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.
- In the Name box, type GreetingCtrl.ascx.
- Switch to Design view in the editor, and then drag a Web Forms Label control from the toolbox to the page.
- In the Properties window, change the ID property of the Label control to Greeting, and then clear the value of the Text property.
- Right-click the page, and then click View Code.
- Add the following private variable declaration to the
code-behind file in the GreetingCtrl class:
private string ctrlGreeting = "Welcome";
- Add the following code to the code-behind file after the
private variable declaration for 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.
public string GreetingMessage { set{ctrlGreeting = value;} get{return ctrlGreeting;} }
- 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
- 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.
- In the Name box, type MenuCtrl.ascx.
- Switch to HTML view in the editor, and then add the
following code: 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.
<%@ 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>
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.
runat="server"
- Right-click the page, and then click View Code.
- 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: 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.
protected NestedUserControls.GreetingCtrl MyGreetingControl; protected System.Web.UI.WebControls.Table MenuTable;
- To programmatically specify menu links, add the following
code to the code-behind class file to include a AddMenuItem method in the MenuCtrl: 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.
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); }
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. - 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;} }
- Replace the existing code in the Page_Load event handler for the MenuCtrl with the following code: This code sets the GreetingMessage property of the GreetingCtrl control to "Howdy." Additionally, this code builds the hyperlinks for the MenuCtrl control.
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"; }
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.- Follow these steps to add a new ASP.NET Web Form that is
named SamplePage.aspx to the project:
- In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.
- In the Name box, type SamplePage.aspx.
- Switch to HTML view in the editor, and then add the
following code: By default, Visual Studio .NET adds the @ Page directive for you.
<%@ 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>
- On the File menu, click Save All to save the Web Form and other files that are associated with the project.
- On the Build menu in the Visual Studio .NET integrated development environment (IDE), click Build Solution to build the project.
- 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?)
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