How to implement nested Web user controls in ASP.NET by using Visual Basic .NET (319100)
The information in this article applies to:
- Microsoft ASP.NET (included with the .NET Framework 1.1)
- Microsoft ASP.NET (included with the .NET Framework) 1.0
- Microsoft Visual Basic .NET (2003)
- Microsoft Visual Basic .NET (2002)
This article was previously published under Q319100 For a Microsoft Visual C# .NET version of this
article, see
317991. IN THIS TASKSUMMARY 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.
- 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 ctrlGreeting As String = "Welcome"
- 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. - 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("Name")
'See if the cookie exists.
If (IsNothing(userName)) Then
Greeting.Text = ctrlGreeting.ToString()
Else
Greeting.Text = String.Format("{0} {1}", ctrlGreeting.ToString(), userName.Value.ToString())
End If
End Sub
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.
- In the Name box, type MenuCtrl.ascx.
- Switch to HTML view in the editor, and then add the
following code:
<%@ Control Language="vb" AutoEventWireup="false" Codebehind="MenuCtrl.ascx.vb" 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"
- 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:
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. - 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. - 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
- 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("Name", "Joe")
Response.Cookies.Add(userName)
AddMenuItem("MSN", "http://www.MSN.com")
AddMenuItem("Microsoft", "http://www.microsoft.com")
AddMenuItem(".NET Development Center", "http://msdn.microsoft.com/netframework/default.aspx")
MyGreetingControl.GreetingMessage = "Howdy"
End Sub
This code sets the GreetingMessage property of the GreetingCtrl control to "Howdy." Additionally, this code builds the hyperlinks
for the MenuCtrl control.
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.
- 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:
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="SamplePage.aspx.vb" 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. - 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.
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 'User Control
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
REFERENCESFor additional information about
ASP.NET development resources, click the article number below to view the
article in the Microsoft Knowledge Base: For more information about how to use ASP.NET Web
user controls, visit the following MSDN Web sites:
back to the top
Modification Type: | Major | Last Reviewed: | 4/14/2006 |
---|
Keywords: | kbCtrlCreate kbHOWTOmaster KB319100 kbAudDeveloper |
---|
|