User Controls (Cont.) - Page 3
August 2, 2002
Example
6-2 shows a page that uses the @ Register
directive and a declarative tag to create the user control shown in Example
6-1. The @ Register directive in Example
6-2 tells ASP.NET to look for any <aspnetian:nav> tags with the runat="server" attribute, and when it finds one, create
an instance of the user control and place its output where the tag is located.
This allows us to place our control very precisely.
Example 6-2: UCClient.aspx <%@ Page Language="vb" %>
<%@ Register TagPrefix="aspnetian" TagName="nav" Src="Nav.ascx" %>
<html>
<head>
</head>
<body>
<table border="1" width="100%" cellpadding="20" cellspacing="0">
<tr>
<td align="center" width="150">
<img src="aspnetian.jpg"/>
</td>
<td align="center">
<h1>User Control Client Page<h1>
</td>
</tr>
<tr>
<td width="150">
<aspnetian:nav runat="server"/>
</td>
<td>
This is where page content might be placed
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
</td>
</tr>
</table>
</body>
</html>
You can instead create the control dynamically using the
LoadControl method and add the control to either the Controls collection of
the page, or, better yet, to the Controls collection of a PlaceHolder control.
The latter allows you to control the location of the user control based on the
location of the placeholder. This technique is shown in Example
6-3.
Example 6-3: UCClient_Prog.aspx <%@ Page Language="vb" %>
<html>
<head>
<script runat="server">
Sub Page_Load( )
PH.Controls.Add(LoadControl("Nav.ascx"))
End Sub
</script>
</head>
<body>
<table border="1" width="100%" cellpadding="20" cellspacing="0">
<tr>
<td align="center" width="150">
<img src="aspnetian.jpg"/>
</td>
<td align="center">
<h1>User Control Client Page<h1>
</td>
</tr>
<tr>
<td width="150">
<asp:placeholder id="PH" runat="server"/>
</td>
<td>
This is where page content might be placed
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
</td>
</tr>
</table>
</body>
</html>
TIP: If you want to work with the control
after loading it using LoadControl, you need to cast the control to the
correct type using the CType function in Visual
Basic .NET or by preceding the control with (typename) in C#. Note that this requires that the user
control be defined in a class that inherits from UserControl, so this
technique would not work with the user control in Example
6-1.
User Controls - Page 2
ASP.NET in a Nutshell
Custom Server Controls - Page 4
|