WindowsDevCenter.com
oreilly.comSafari Books Online.Conferences.

advertisement


AddThis Social Bookmark Button O'Reilly Book Excerpts: Programming ASP.NET

Chapter 14: Custom and User Controls

Related Reading

Programming ASP .NET
By Jesse Liberty, Dan Hurwitz

Chapter 4 includes a chart of the five types of controls supported in ASP.NET: HTML controls, HTML server controls, web server controls, validation controls, and controls created by the developer. This chapter will discuss this last type of control, known as custom controls, and a subset of them called user controls.

Custom controls are compiled controls that act, from the client's perspective, much like web (ASP) controls. Custom controls can be created in one of three ways:

  • By deriving a new custom control from an existing control (e.g., deriving your own specialized text box from asp:textbox). This is known as a derived custom control.
  • By composing a new custom control out of two or more existing controls. This is known as a composite custom control.
  • By deriving from the base control class, thus creating a new custom control from scratch. This is known as a full custom control.

Of course, all three of these methods, and the three control types that correspond to them, are variations on the same theme. We'll consider these custom controls later in this chapter. The simplest category of custom controls is a subset called user controls. Microsoft distinguishes user controls as a special case because they are quite different from other types of custom controls. In short, user controls are segments of ASP.NET pages that can be reused from within other pages. This is similar to "include files" familiar to ASP developers. However, user controls are far more powerful. User controls support properties and events, and thus provide reusable functionality as well as reusable HTML.

User Controls

User controls allow you to save a part of an existing ASP.NET page and reuse it in many other ASP.NET pages. A user control is almost identical to a normal .aspx page, with two differences: the user control has the .ascx extension rather than .aspx, and it may not have <HTML>, <Body>, or <Form> tags.

The simplest user control is one that displays HTML only. A classic example of a simple user control is an HTML page that displays a copyright notice. Example 14-1 shows the complete listing for copyright.ascx.

Example 14-1: copyright.ascx

<%@ Control %>
<hr>
<table>
   <tr>
      <td align="center">Copyright 2005 Liberty Associates, Inc.</td>
   </tr>
   <tr>
      <td align="center">Support at http://www.LibertyAssociates.com</td>   
   </tr>
</table>

To see this at work, you'll modify Example 8-1, adding just two lines. At the top of the .aspx file, you'll add the registration of your new user control:

<%@Register tagprefix="OReilly" Tagname="copyright" src="copyright.ascx" %> 

This registers the control with the page and establishes both the prefix (OReilly) and the TagName (copyright). In the page you are modifying, there are any number of ASP elements such as <asp:ListItem>. The letters asp before the colon are the tag prefix that identifies this tag as being a web control, and the token ListItem is the TagName.

Your user controls will have a tag prefix as well (in this case, Oreilly), in addition to a specific tag name (in this case, copyright). Interestingly, there is nothing in the .ascx file itself that identifies the tag prefix.

The modified .aspx code is shown in Example 14-2. The output from this page is shown in Figure 14-1.

Figure 14-1. The copyright user control

 

Example 14-2: Modification of Example 8-1

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" 
AutoEventWireup="false" Inherits="Validation04.WebForm1" %>
 
<%@Register tagprefix="OReilly" Tagname="copyright" src="copyright.ascx" %>
 
<HTML>
  <HEAD>
 
<!-- Demonstrate simple required field validation -->
      <meta name=vs_targetSchema content="Internet Explorer 5.0">
      <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
      <meta name="CODE_LANGUAGE" Content="C#">
  </HEAD>
   <body>
      <h3>
         <font face="Verdana">Bug Report</font>
      </h3>
      <form runat="server" ID="frmBugs">
         <table bgcolor=gainsboro cellpadding=10>
            <tr valign="top">
               <td colspan=3>
                  <!-- Display error messages -->
                  <asp:Label ID="lblMsg" 
                  Text="Please report your bug here" 
                  ForeColor="red" Font-Name="Verdana" 
                  Font-Size="10" runat=server />
                  <br>
               </td>
            </tr>
            <tr>
               <td align=right>
                  <font face=Verdana size=2>Book</font>
               </td>
               <td>
               <!-- Drop down list with the books (must pick one) -->
                  <ASP:DropDownList id=ddlBooks runat=server>
                     <asp:ListItem>-- Please Pick A Book --</asp:ListItem>
                     <asp:ListItem>Programming ASP.NET</asp:ListItem>
                     <asp:ListItem>Programming C#</asp:ListItem>
                     <asp:ListItem>
                        Teach Yourself C++ In 21 Days
                     </asp:ListItem>
                     <asp:ListItem>
                        Teach Yourself C++ In 24 Hours
                     </asp:ListItem>
                     <asp:ListItem>TY C++ In 10 Minutes</asp:ListItem>
                     <asp:ListItem>TY More C++ In 21 Days</asp:ListItem>
                     <asp:ListItem>C++ Unleashed</asp:ListItem>
                     <asp:ListItem>C++ From Scratch</asp:ListItem>
                     <asp:ListItem>XML From Scratch</asp:ListItem>
                     <asp:ListItem>Web Classes FS</asp:ListItem>
                     <asp:ListItem>Beg. OO Analysis & Design</asp:ListItem>
                     <asp:ListItem>Clouds To Code</asp:ListItem>
                     <asp:ListItem>
                        CIG Career Computer Programming
                     </asp:ListItem>
                  </ASP:DropDownList>
               </td>
               <!-- Validator for the drop down -->
               <td align=middle rowspan=1>
                  <asp:RequiredFieldValidator 
                  id="reqFieldBooks" 
                  ControlToValidate="ddlBooks" 
                  Display="Static" 
                  InitialValue="-- Please Pick A Book --" 
                  Width="100%" runat=server>
                     Please choose a book
                  </asp:RequiredFieldValidator>
               </td>
            </tr>
            <tr>
               <td align=right>
               <!-- Radio buttons for the edition -->                  
                  <font face=Verdana size=2>Edition:</font>
               </td>
               <td>
                  <ASP:RadioButtonList id=rblEdition 
                  RepeatLayout="Flow" runat=server>
                     <asp:ListItem>1st</asp:ListItem>
                     <asp:ListItem>2nd</asp:ListItem>
                     <asp:ListItem>3rd</asp:ListItem>
                     <asp:ListItem>4th</asp:ListItem>
                  </ASP:RadioButtonList>
               </td>
               <!-- Validator for editions -->
               <td align=middle rowspan=1>
                  <asp:RequiredFieldValidator 
                  id="reqFieldEdition" 
                  ControlToValidate="rblEdition" 
                  Display="Static" 
                  InitialValue="" 
                  Width="100%" runat=server>
                     Please pick an edition
                  </asp:RequiredFieldValidator>
               </td>
            </tr>
            <tr>
               <td align=right style="HEIGHT: 97px">
                  <font face=Verdana size=2>Bug:</font>
               </td>
               <!-- Multi-line text for the bug entry -->               
               <td style="HEIGHT: 97px">
                  <ASP:TextBox id=txtBug runat=server width="183px" 
                  textmode="MultiLine" height="68px"/>
               </td>
               <!-- Validator for the text box-->               
               <td style="HEIGHT: 97px">
                  <asp:RequiredFieldValidator 
                  id="reqFieldBug" 
                  ControlToValidate="txtBug" 
                  Display="Static" 
                  Width="100%" runat=server>
                     Please provide bug details
                  </asp:RequiredFieldValidator>
               </td>
            </tr>
            <tr>
               <td>
               </td>
               <td>
                  <ASP:Button id=btnSubmit 
                  text="Submit Bug" runat=server />
               </td>
               <td>
               </td>
            </tr>
         </table>
      </form>
<OReilly:copyright runat="server" />
   </body>
</HTML> 

In Figure 14-1 the horizontal rule at the bottom of the page, and the copyright notice below it, comes from the .ascx user control you've created. This control can be reused in many pages. If you update the copyright, you will make that update only in the one .ascx file, and it will be displayed appropriately in all the pages that use that control.

In the next example, you will recreate the book drop-down list itself, this time as a user control. The process of converting part of an existing HTML page into a user control is very simple; you just extract the code that creates the drop-down list into its own HTML file and name that file with the .ascx extension.

Visual Studio .NET provides support for creating user controls. Right-click on the project and choose Add Add New Item. One of the choices is New User Control. This choice opens a new form. The HTML at the top of the form includes the Control directive, which sets the language attributes, etc.

Rename the new item BookList.ascx and copy in the code for creating the book list, as shown in Example 14-3.

Example 14-3: The BookList user control

<!-- Drop down list with the books (must pick one) -->
   <ASP:DropDownList id=ddlBooks runat=server>
      <asp:ListItem>-- Please Pick A Book --</asp:ListItem>
      <asp:ListItem>Programming ASP.NET</asp:ListItem>
      <asp:ListItem>Programming C#</asp:ListItem>
      <asp:ListItem>
         Teach Yourself C++ In 21 Days
      </asp:ListItem>
      <asp:ListItem>
         Teach Yourself C++ In 24 Hours
      </asp:ListItem>
      <asp:ListItem>TY C++ In 10 Minutes</asp:ListItem>
      <asp:ListItem>TY More C++ In 21 Days</asp:ListItem>
      <asp:ListItem>C++ Unleashed</asp:ListItem>
      <asp:ListItem>C++ From Scratch</asp:ListItem>
      <asp:ListItem>XML From Scratch</asp:ListItem>
      <asp:ListItem>Web Classes FS</asp:ListItem>
      <asp:ListItem>Beg. OO Analysis & Design</asp:ListItem>
      <asp:ListItem>Clouds To Code</asp:ListItem>
      <asp:ListItem>
         CIG Career Computer Programming
      </asp:ListItem>
   </ASP:DropDownList>

TIP:   In Example 14-3, you'll strip out the validator code, to keep the focus on working with the user control. The validator can be used with the user control exactly as it was with the ASP control.

To make this work in your page, you'll add a new Register statement:

<%@Register tagprefix="OReilly" Tagname="bookList" src="bookList.ascx" %>

In the body of the page, you'll add the new user control, exactly where you cut the original code:

<OReilly:bookList runat="server" ID="Booklist"/>

Pages: 1, 2, 3, 4

Next Pagearrow