User Controls

Imagine the requirement for a common look and feel across all the pages of a Web site for certain portions of each page. This will only apply to one site, so there won't be any reason to waste time making something so generic that it could be used elsewhere. It should be quick to do and not very complicated. However, it should have enough facilities that would make it robust and powerful to accomplish whatever user interface task was required. What has just been described is a requirement that would be implemented well with a user control.

User controls are reusable components that you can create in the ASP.NET visual designer. After you've created the control, you can reuse it on multiple pages in the same project. In the visual designer, user controls are created as composites of other controls. They are designed in the same way as a normal ASP.NET Web page, but have Control directives, have less HTML infrastructure, and are named with an .ascx file extension.

Good examples of user controls are for menus, page headers, and page footers. They are specific to a site but can be used in multiple places. This section will demonstrate user controls by creating a reusable header control.

In setting up this example, it is necessary to create a new ASP.NET project. See Chapter 11, "Introduction to ASP.NET," for information on creating ASP.NET projects. I named this project example PageHeader and changed the name of the default Web form from WebForm1.aspx to Default.aspx. Remember to set the PageLayout property of the Document object in the Object Inspector to FlowLayout. After the project is set up, the new user control will be added to the same project.

Creating a User Control

To create a new user control, be sure to select the project it will be placed in. I normally select the project title, but one of the files within the project will work also. Select File, New, Other to bring up the New Items dialog. The User Control Wizard is located in the C# ASP Files folder, under the C# ASP Projects folder. Starting the ASP.NET User Control Wizard will simply add a new file, WebUserControl1, to the PageHeader project.

Change the new user control name by selecting the control file in the Project Manager, waiting a second, and then selecting the text. This puts the file in edit mode where its name can be changed to "HeaderControl.ascx". Now the control is ready to build, a task that will be performed visually. To change the control, select WebUserControl1 from the Object Inspector drop-down list, and change the Name property to "HeaderControl".

There is an Insert Table button on the toolbar above the Designer Surface. Because tables are very handy for structuring Web page components, they will be used in this example. Click the Insert Table button to bring up the Insert Table dialog (see Figure 14.1). The sections on this dialog are for setting the number of columns and rows, setting table attributes, and setting attributes for each cell in the table. Most items are self-explanatory and correspond to what would be expected with an HTML table, but clicking the Help button will bring up more information for the curious. This example only uses a few of these options, which should give an idea of how the Insert Table options work.

Figure 14.1. The Insert Table dialog.

graphics/14fig01.gif

The control will contain a picture on the left of the screen and a header title that is centered across the rest of the screen. To accomplish this, set the Rows to 1 and Columns to 2. In the Table Attributes section, change the Width measurement from Pixels to Percent. The width will change from 300 to 100, which makes the table adjust to the full width of the user's browser. Within the Table Attributes section there is another option called Border Size, which should be changed from one to zero. The borders will not be visible to the client, but they will be visible in the designer. Click the OK button to close the dialog. Some of the styles found in the Insert Table dialog may be subsequently changed by locating the table element you want to change and modifying its value in the Object Inspector. Before inserting the image into the control, modify the first cell's width by opening the HeaderControl.ascx file and adding a style attribute, style="WIDTH: 125px", to the first column (<td>).

To insert an image into the control, select the left cell in the newly created table to set where the image will be inserted. There is another button on the toolbar above the Designer Surface called Insert Image. Clicking this button brings up the Insert Image dialog (see Figure 14.2).

Figure 14.2. The Insert Image dialog.

graphics/14fig02.gif

The options on this dialog correspond to options available for an HTML IMG tag, and more info can be obtained by clicking the Help button. Click the Browse button to the right of the Image Source, which brings up an Open File dialog, and select the image that will be placed in the cell. After you choose the image, click the OK button and the image will appear in the left cell. The cell will adjust to accommodate the size of the picture. Select the picture in the left cell and then click the Center button in the toolbar above the designer to center the image.

In the right cell, type the words User Control Demo. Highlight those words and click the Center button on the toolbar above the designer surface. Another toolbar above the designer surface controls font styles used for text, which are used to change attributes of the highlighted text. While the text is still highlighted, click the Font Foreground Color button and change the color to Blue. Then change the style to Heading 1. Figure 14.3 shows the completed user control. The picture in this example (see Figure 14.3) was created with MS-Paint, and saved in GIF format with a size of 90x90.

Figure 14.3. The HeaderControl user control.

graphics/14fig03.gif

Before actually using this HeaderControl, it will be instructive to look at the code that C#Builder created. The most interesting code is in the HeaderControl.ascx file (see Listing 14.1).

There are two things to notice immediately when looking at the code in Listing 14.1: the Control directive and the lack of HTML framing tags. Instead of a Page directive, a user control contains a Control directive at the top of the file. Table 14.1 shows the available attributes for Control directives. The second item that is noticeable in Listing 14.1 is that there are no HTML framing tags; that is, no <html><head></head><body></body></html> tags. The control simply consists of the HTML that will be injected into the Web Form as is.

Listing 14.1 Web Form Code for the HeaderControl User Control (HeaderControl.ascx)

 <%@ Control Language="c#" AutoEventWireup="false" Codebehind="HeaderControl.ascx.cs" Inherits="PageHeader.HeaderControl"%> <table  cellspacing="1" cellpadding="1"        width="100%" border="0">   <tbody>     <tr>       <td style="WIDTH: 125px">         <p align="center">           &nbsp;<img alt="" hspace="0" src="file:///C:\Documents%20and%20Settings\Joe\My%20Documents\ C#%20Builder graphics/ccc.gif\Chapter14\Code\PageHeader\PeaceBaby.GIF"              border="0">         </p>       </td>       <td>         <h1 align="center">           <font color="blue">User Control Demo</font>         </h1>       </td>     </tr>   </tbody> </table> 

Table 14.1. Control Directive Attributes

ATTRIBUTE NAME

PURPOSE

AutoEventWireup

Automatically hooks up page events when true. That is, C#Builder won't need to hook up the event handler in the InitializeComponent method.

ClassName

Name of page to use for dynamic compilation.

CompilerOptions

Command-line switches to use when compiling control.

Debug

Compiles page with debug symbols if set to true.

Description

Text description of what control does.

EnableViewState

Turns off view state if set to false.

Explicit

Compiles page as Option Explicit for VB.NET code.

Inherits

Code-behind file this control inherits from.

Language

Language for inline code. Set to C# for C#Builder.

Strict

Sets the Option Strict mode for VB.NET code.

Src

Code-behind file used for dynamic compilation.

WarningLevel

Compiler warning level at which to abort compilation.

The code-behind file for this user control only has a default implementation (see Listing 14.2).

Listing 14.2 Code-Behind for HeaderControl User Control (HeaderControl.ascx.cs)
 using System; using System.Data; using System.Drawing; using System.Web; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace PageHeader {    /// <summary>    /// Summary description for HeaderControl.    /// </summary>    public abstract class HeaderControl : System.Web.UI.UserControl    {       private void Page_Load(object sender, System.EventArgs e)       {          // Put user code to initialize the page here       }       #region Web Form Designer generated code       override protected void OnInit(EventArgs e)       {          //          // CODEGEN: This call is required by the ASP.NET Web Form Designer.          //          InitializeComponent();          base.OnInit(e);       }       /// <summary>       /// Required method for Designer support - do not modify       /// the contents of this method with the code editor.       /// </summary>       private void InitializeComponent()       {          this.Load += new System.EventHandler(this.Page_Load);       }       #endregion    } } 

There are a few items to note in Listing 14.1: the fully qualified name, inheritance, and event handling. The code-behind class in Listing 14.2 is named HeaderControl and is scoped to the PageHeader namespace, which corresponds to the Inherits attribute in the Control directive from Listing 14.1. The second thing to notice is that the code-behind inherits from System.Web.UI.UserControl, which designates this as a user control. Third, because the AutoEventWireup attribute of the Control directive in Listing 14.1 is set to false, the Page_Load event handler is hooked up to the Load event in the InitializeComponent method. Had AutoEventWireup been set to true, C#Builder would not have needed to add the event handler hook up code to the InitializeComponent method and the Load event would have automatically called Page_Load when fired.

The control is now complete and can be added to any Web page in the project.

Adding a User Control to a Web Form

User controls are added by selecting Insert, Insert User Control and either typing in a fully qualified path, selecting a user control from the drop-down list, or selecting the Browse button and locating the user control file. Because there isn't anything in the Default.aspx Web Form and it is set to FlowLayout, dropping the HeaderControl user control positions it in the top left corner of the Web Form (see Figure 14.4). A user control doesn't display its real appearance on the designer surface; rather, it appears as a rectangle control with the control name.

Figure 14.4. A user control on the designer surface.

graphics/14fig04.gif

Within the Web Form code, the user control appears as a tag and a Register directive is added at the top of the file, below the Page directive. Listing 14.3 shows what the Web Form code looks like after a user control has been added.

Listing 14.3 Web Form Code with a User Control (Default.aspx)
 <%@ Page language="c#" Debug="true" Codebehind="Default.aspx.cs" AutoEventWireup="false" Inherits="PageHeader.WebForm1" %> <%@ Register TagPrefix="csb" TagName="HeaderControl" src="/books/2/805/1/html/2/HeaderControl.ascx" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title></title>     <meta name="GENERATOR" content="Borland ASP.NET Designer for c# Package Library 7.1">   </head>   <body ms_positioning="FlowLayout">     <form runat="server">       <csb:headercontrol  runat="server">       </csb:headercontrol>     </form>   </body> </html> 

The two parts of Listing 14.3 to pay attention to are the Register directive and the headercontrol tag. When the user control was added to the Web Form, C#Builder added the Register directive to the top of the file. Table 14.2 lists the available attributes for the Register directive. The TagPrefix attribute identifies the prefix of the tag that will be added to the code. Because it is set to "csb", the headercontrol tag within the form element of the code will have a prefix of "csb:". I changed the default name assigned by C#Builder to csb (C#Builder abbreviated) to show that it can be anything the developer wants it to be. The rest of the tag will be the same as the TagName attribute, HeaderControl. As you can see, there is no case sensitivity between the Register directive attributes and the tag in the code. Finally, the Src attribute associates the tag identified by the TagPrefix and TagName with the user control code file. Normally, a TagPrefix associates a set of user controls. For example, there could be a group of controls with TagName attributes set to HeaderControl, FooterControl, and MenuControl, and all of their TagPrefix attributes could be set to csb. The tag prefix helps qualify the control name to avoid clashes between similarly named controls in different libraries.

Table 14.2. Register Directive Attributes

ATTRIBUTE NAME

PURPOSE

TagPrefix

An identifier associated with a namespace.

TagName

An identifier associated with a class.

Namespace

A namespace associated with a Tagprefix.

Src

The path of the user control file.

Assembly

The name of the assembly, without a suffix, identifying where Namespace is defined.

The code-behind file for this example is not changed by addition of the user control. Figure 14.5 shows the execution of the page with the user control added. This user control can be added to multiple pages. Then whenever a change needs to be made to the header, change the control only and all the pages it has been added to will have the new modifications.

Figure 14.5. A user control displayed on a Web Form.

graphics/14fig05.gif



C# Builder KickStart
C# Builder KickStart
ISBN: 672325896
EAN: N/A
Year: 2003
Pages: 165

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net