Chapter 10
If you look at the actual page that is sent to the server, you can see the user control is included with a simple two lines of code that we’ve highlighted (this source code page is available for download at www.wrox.com):
<%@ Page Language=”VB” MasterPageFile=”~/site.master” AutoEventWireup=”false” codefile=”Default.aspx.vb” Inherits=”_Default” %>
<%@ Register TagPrefix=”uc1” TagName=”News” Src=”News.ascx” %>
<asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”server”>
<h2>Welcome to the Wrox United Web site.</h2>
<p>We’re a great football team. No really, we are. Don’t take any notice of our past performance. We’re just unlucky.</p>
<uc1:news id=”News1” runat=”server” ItemsToShow=”3”></uc1:news>
</asp:Content>
This page starts giving you some clues as to how user controls work.
User Control Structure
User controls are stored in separate files with a separate .ascx extension. Any time you see this extension you know that you are dealing with a user control. To create a user control you need to add a @Register directive to the top of your Web Form identifying where you can find your user control:
<%@Register TagPrefix=”WroxUnited” TagName=”MyControl” %>
You need to add a new tag specifying where the control will go on your page. It will be composed of the TagPrefix, followed by a colon, followed by the TagName, an ID, and the now familiar runat=server attribute:
<WroxUnited:MyControl id=”mycontrol1” runat=”server”>
</WroxUnited:MyControl>
Lastly, you need to specify the user control itself in a separate .ascx file. Unlike Web Forms, you don’t need to specify extra <html> and <body> tags, because the contents of this control will be added to the body of the containing main page. In fact, all you need to have is the controls themselves that you want to include. For example, you could include the controls from the code-behind example used earlier in the chapter:
<asp:Label ID=”Label1” runat=”server” Text=”What is the answer to the meaning of life, the universe and everything?:”></asp:Label>
<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox> <br /><br />
<asp:Button ID=”Button1” runat=”server” Text=”Submit” /> <br />
<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>
Of course, user controls can have code-behind files as well, just like Web Forms: