Recipe 6.3. Creating a Custom Control with Attributes


Problem

You want to create a custom control with HTML-style attributes that can be used to customize the appearance of the control in the .aspx file.

Solution

Create the basic custom control (as described in Recipe 6.1), add properties to the class, and use the values of the properties when rendering the control's HTML output.

Use the .NET language of your choice to:

  1. Create a class that inherits from the WebControl class in the System.Web.UI.WebControls namespace.

  2. Implement support for the HTML-style attributes by adding properties to the class.

  3. Override the TagKey property to return the HTML tag to be used as a container for the control.

  4. Override the RenderContents method to have it render the HTML output of the control using the values of the properties.

To use the custom control in an ASP.NET page:

  1. Register the assembly containing the control.

  2. Insert the tag for the custom control anywhere in the page and set the attributes appropriately.

To illustrate this solution, we started with the sample custom control we built for Recipe 6.1 and added support for HTML-style attributes, such as an attribute that defines the color used to display label text. Figure 6-2 shows some output using default and modified attributes for the control. In the case of the latter, we used the Enter Age: label text appears in red when rendered on the screen. Examples 6-4 and 6-5 show the VB and C# class files for our custom control. Example 6-6 shows how to use the custom control in an ASP.NET page to produce these results.

Figure 6-2. Custom control with attributes output


Discussion

Recipe 6.1 describes how to create a basic custom control, so we'll skip that discussion here. Instead, we'll focus on implementing HTML-style attributes for a custom control.

Custom control properties provide the ability to change aspects of the control programmatically using HTML-style attributes, which can be set in the .aspx file or code-behind. Attributes are a common feature of ASP.NET server controls. For example, the image button control provides an ImageURL attribute that you can set to define the image to be displayed when the control is rendered:

 <asp:ImageButton ; Runat="server" ImageUrl="button_submit.gif" /> 

Attributes are implemented in a custom control by adding properties to the class. The properties are similar to properties in a class implemented as a data service. The names of the properties define the names of the attributes that can be used with the custom control.

To illustrate this approach, we've provided the code in Examples 6-4 (VB) and 6-5 (C#) that defines a custom control named CH06CustomControlAttributesVB or CH06-CustomControlAttributesCS with the properties shown in Table 6-1.

Table 6-1. Custom control properties

Property

Data type

Description

labelText

String

Defines the text for the label

textColor

Color

Defines the color used to display the label text

textboxWidth

Int or Integer

Defines the width of the text box


When you define custom control properties, you should always initialize each property by assigning it a default value. For example, in Examples 6-4 and 6-5, we've assigned the private variable used to store the labelText property an initial value of "Label:", the private variable used to store the textColor property value has been given an initial value of Color.Black, and the private variable used to store the textboxWidth property value has been given an initial value of 3. Initializing properties in this manner allows your control to handle the condition when the programmer does not include a value for the attribute that corresponds to a particular property.

To use a custom control, it must first be registered in the target .aspx file, as described in Recipe 6.1. For instance, here's how to register the VB version of the custom control in our example:

 <%@ Register TagPrefix="ASPCookbook" Namespace="ASPNetCookbook.VBExamples" %> 

You can use the control as is if the default label text, text color, and text box width are acceptable:

 <ASPCookbook:CH06CustomControlAttributesVB  runat="server" /> 

Or you can set the attributes to customize the look of the control for a particular page:

 <ASPCookbook:CH06CustomControlAttributesVB  runat="server" labelText = "Enter Age: " textColor="#ff0000" textboxWidth="10" Css /> 

One thing to consider when implementing the properties of a custom control is that ASP.NET will match the names of the attributes in the custom control tag (.aspx file) with the names of the properties in the class that implements the custom control. What's more, because all attribute values in the .aspx file are strings, ASP.NET provides the type conversion necessary to match the type required for the property.

If ASP.NET cannot convert the attribute value to the type required for the property, a parse exception will be thrown when the page is displayed. For example, if a property is an integer type and the value "abc" is set as the attribute value, a parse exception will be thrown. If you set the attributes in the .aspx file, there will be no way to prevent this other than to ensure you test the code. Alternately, you can set the values in the code-behind, which will generally catch errors of this type during compilation instead of at runtime.


By default, a custom control that derives from WebControl is rendered within an HTML <span> tag. You can change the HTML container by overriding the TagKey property and returning the desired HTML tag, as we have done in our example where we use a <div> tag as the container instead. You'll see in a minute how this plays out in the HTML that is rendered.

 

Protected Overrides ReadOnly Property TagKey() As HtmlTextWriterTag Get Return (HtmlTextWriterTag.Div) End Get End Property 'TagKey

protected override HtmlTextWriterTag TagKey { get { return (HtmlTextWriterTag.Div); } } // TagKey

When deriving your custom control from WebControl, you should override the RenderContents method to output the contents of your control. The RenderContents method is called after the Render method has rendered the HTML tag (and its attributes) used as the container for your control. By using this approach, any attributes included in the control in the .aspx file will be output as attributes of control container. In our example, we have included an attribute for the CssClass:

 <ASPCookbook:CH06CustomControlAttributesVB  runat="server" labelText = "Enter Age: " textColor="#ff0000" textboxWidth="10" Css /> 

If you override the Render method, the RenderContents method will not be called, since the Render method sets up the rendering execution life cycle. Generally, you should override only the RenderContents method.


When the control is rendered, the following HTML is sent to the browser with the class attribute set to the value of the CssClass attribute in the server control:

 <div   > <font color="Red">Enter Age: </font><input type="text" size="10" /> </div> 

See Also

Recipe 6.1

Example 6-4. Custom control with attributes (.vb)

 Option Explicit On Option Strict On Imports System.Drawing Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides a custom control with attributes to provide the ''' ability to alter the control programmically. ''' </summary> Public Class CH06CustomControlAttributesVB Inherits WebControl 'private copies of attribute data Private mLabelText As String = "Label: " Private mTextColor As Color = Color.Black Private mTextboxWidth As Integer = 3 '''********************************************************************** ''' <summary> ''' This property provides the ability to get/set the text of of the label ''' in the control ''' </summary> Public Property labelText() As String Get Return (mLabelText) End Get Set(ByVal Value As String) mLabelText = Value End Set End Property 'labelText '''*********************************************************************** ''' <summary> ''' This property provides the ability to set the color of the text ''' in the control ''' </summary> Public Property textColor() As Color Get Return (mTextColor) End Get Set(ByVal Value As Color) mTextColor = Value End Set End Property 'textColor '''*********************************************************************** ''' <summary> ''' This property provides the ability to get/set the width of the text box ''' in the control ''' </summary> Public Property textboxWidth() As Integer Get Return (mTextboxWidth) End Get Set(ByVal Value As Integer) mTextboxWidth = Value End Set End Property 'textboxWidth '''*********************************************************************** ''' <summary> ''' This property provides the ability to set the HTML tag that is used ''' as the container for the control ''' </summary> Protected Overrides ReadOnly Property TagKey() As HtmlTextWriterTag Get Return (HtmlTextWriterTag.Div) End Get End Property 'TagKey '''*********************************************************************** ''' <summary> ''' This routine renders the HTML output of the control contents ''' </summary> ''' ''' <param name="writer">Set to the HtmlTextWriter to use to output the ''' rendered HTML for the control ''' </param> Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter) 'output label within a font tag writer.AddAttribute("color", _ ColorTranslator.ToHtml(textColor)) writer.RenderBeginTag(HtmlTextWriterTag.Font) writer.Write(labelText) writer.RenderEndTag() 'output input control writer.AddAttribute(HtmlTextWriterAttribute.Type, _ "text") writer.AddAttribute(HtmlTextWriterAttribute.Size, _ textboxWidth.ToString()) writer.RenderBeginTag(HtmlTextWriterTag.Input) writer.RenderEndTag() End Sub    'RenderContents End Class    'CH06CustomControlAttributesVB End Namespace 

Example 6-5. Custom control with attributes (.cs)

 using System; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides a custom control with attributes to provide the /// ability to alter the control programmically. /// </summary> public class CH06CustomControlAttributesCS : WebControl { // private copies of attribute data private String mLabelText = "Label: "; private Color mTextColor = Color.Black; private int mTextboxWidth = 3; ///********************************************************************** /// <summary> /// This property provides the ability to get/set the text of of the label /// in the control /// </summary> public String labelText { get { return (mLabelText); } set { mLabelText = value; } } // labelText ///*********************************************************************** /// <summary> /// This property provides the ability to set the color of the text /// in the control /// </summary> public Color textColor { get { return (mTextColor); } set { mTextColor = value; } } // textColor ///*********************************************************************** /// <summary> /// This property provides the ability to get/set the width of the text box /// in the control /// </summary> public int textboxWidth { get { return (mTextboxWidth); } set { mTextboxWidth = value; } } // textboxWidth ///*********************************************************************** /// <summary> /// This property provides the ability to set the HTML tag that is used /// as the container for the control /// </summary> protected override HtmlTextWriterTag TagKey { get { return (HtmlTextWriterTag.Div); } } // TagKey ///*********************************************************************** /// <summary> /// This routine renders the HTML output of the control contents /// </summary> /// /// <param name="writer">Set to the HtmlTextWriter to use to output the /// rendered HTML for the control /// </param> protected override void RenderContents(HtmlTextWriter writer) { // output label within a font tag writer.AddAttribute("color", ColorTranslator.ToHtml(textColor)); writer.RenderBeginTag(HtmlTextWriterTag.Font); writer.Write(labelText); writer.RenderEndTag(); // output input control writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Size, textboxWidth.ToString()); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); } // RenderContents } // CH06CustomControlAttributesCS } 

Example 6-6. Using the custom control with attributes (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH06DisplayControlWithAttributesVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH06DisplayControlWithAttributesVB" Title="Display Custom Control With Attributes" %> <%@ Register TagPrefix="ASPCookbook" Namespace="ASPNetCookbook.VBExamples" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Custom Control With Attributes (VB) </div> <table width="90%" align="center" border="0"> <tr> <td>With Default Attributes:</td> </tr> <tr bgcolor="#ffffcc"> <td align="center"> <ASPCookbook:CH06CustomControlAttributesVB  runat="server" /> </td> </tr> <tr> <td><br />With Modified Attributes:</td> </tr> <tr bgcolor="#ffffcc"> <td align="center"> <ASPCookbook:CH06CustomControlAttributesVB  runat="server" labelText = "Enter Age: " textColor="#ff0000" textboxWidth="10" Css /> </td> </tr> <tr> <td align="center"> <br/> <asp:Button  runat="server" Text="Submit" /> </td> </tr> </table> </asp:Content> 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

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