Chapter 10
You need to add a new tag specifying where the control will go on your page. It consists 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 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:
public void Page_Load( object sender, System.EventArgs e)
{
if (Page.IsPostBack)
{
if (TextBox1.Text == “42”)
Label2.Text = “So you read Douglas Adams as well...”;
else
{
Label2.Text = “No, I’m not sure that’s it”;
}
}
This control can then be bolted into your web pages wherever you specify the @Register directive and add a tag for the control.
A Simple User Control
In the next Try It Out, you’re going to start by creating a trivial “Hello World”-style user control to get you used to the idea of including them in your pages. This code does no more than encapsulate the code-behind from the first example you created in the chapter as a user control. You’ll see how you can place the user control in one web page, and then in a second web page.
Try It Out |
Creating a Simple User Control |
1.Open VWD and create a new ASP.NET web site called SimpleUserControl in the chapter directory (C:\BegASPNET\Chapters\Begin\Chapter10).
2.In Solution Explorer, right-click the web site and select Add New Item. Select Web User Control, enter the name SimpleUserControl.ascx, and check the Place Code in Separate File option, as shown in Figure 10-18.