Recipe 5.2 Creating a Custom Control with Attributes

     

5.2.1 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.

5.2.2 Solution

Create the basic custom control (as described in Recipe 5.1), add properties to the class, and then 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 Control class in the System.Web.UI namespace.

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

  3. Override the Render 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 5.1 and then added support for HTML-style attributes, such as an attribute that defines the color used to display label text. Figure 5-2 shows some output using default and modified attributes for the control; in the case of the latter, the Enter Age: label text actually appears in red when rendered on the screen. Example 5-4 and Example 5-5 show the VB and C# class files for our custom control. Example 5-6 shows how to use the custom control in an ASP.NET page to produce these results.

Figure 5-2. Custom control with attributes output
figs/ancb_0502.gif

5.2.3 Discussion

Recipe 5.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 programmatically change aspects of the control 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 that is to be displayed when the control is rendered:

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

Attributes are implemented in a custom control by adding properties to the class. The properties are no different than properties in a class implemented as a business or 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 Example 5-4 (VB) and Example 5-5 (C#) that defines a custom control named CustomControlAttributesVB or CustomControlAttributesCS with the properties shown in Table 5-1.

Table 5-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 Example 5-4 and Example 5-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 5.1. For instance, here's how to register the VB version of the custom control in our example:

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

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

 <ASPCookbook:CH05CustomControlAttributesVB id="ccAttributes1" runat="server" /> 

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

 <ASPCookbook:CH05CustomControlAttributesVB id="ccAttributes2" runat="server"  labelText = "Enter Age: "   textColor="#FF0000"   textboxWidth="10" />  

Before a custom control's attributes can be set in the code-behind, the control must first be declared, just like any other server control. For example, here's how you declare the custom control in the code-behind of our sample application and then set the control's textColor attribute to green:

 
figs/vbicon.gif
 Protected ccAttributes1 As CustomControlAttributesVB .. ccAttributes1.textColor = Color.Green 
figs/csharpicon.gif
 protected CustomControlAttributesCS ccAttributes1; .. ccAttributes1.textColor = Color.Green; 

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 effectively 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 really is no way to prevent this other than to make sure you test the code thoroughly. Alternately, you can set the values in the code-behind, which will generally catch errors of this type during compilation instead of at runtime.


5.2.4 See Also

Recipe 5.1

Example 5-4. Custom control with attributes (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name : CH05CustomControlAttributesVB.vb ' ' Description: This class provides a custom control with attributes to ' provide the ability to alter the control programmically. ' '***************************************************************************** Imports System Imports System.drawing Imports System.Web Imports System.Web.UI Namespace ASPNetCookbook.VBExamples Public Class CH05CustomControlAttributesVB Inherits Control  'private copies of attribute data   Private mLabelText As String = "Label: "   Private mTextColor As Color = Color.Black   Private mTextboxWidth As Integer = 3  '************************************************************************* ' ' ROUTINE: labelText ' ' DESCRIPTION: This property provides the ability to set the text of ' of the label in the control '-------------------------------------------------------------------------  Public Property labelText( ) As String   Get   Return (mLabelText)   End Get   Set(ByVal Value As String)   mLabelText = Value   End Set   End Property 'labelText  '************************************************************************* ' ' ROUTINE: textColor ' ' DESCRIPTION: This property provides the ability to set the color ' of the text in the control '-------------------------------------------------------------------------  Public Property textColor( ) As Color   Get   Return (mTextColor)   End Get   Set(ByVal Value As Color)   mTextColor = Value   End Set   End Property 'textColor  '************************************************************************* ' ' ROUTINE: textboxWidth ' ' DESCRIPTION: This property provides the ability to set the width ' of the textbox in the control '-------------------------------------------------------------------------  Public Property textboxWidth( ) As Integer   Get   Return (mTextboxWidth)   End Get   Set(ByVal Value As Integer)   mTextboxWidth = Value   End Set   End Property 'textboxWidth  '************************************************************************* ' ' ROUTINE: Render ' ' DESCRIPTION: This routine renders the HTML output of the control '------------------------------------------------------------------------- Protected Overrides Sub Render(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 'Render End Class 'CH05CustomControlAttributesVB End Namespace 

Example 5-5. Custom control with attributes (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH05CustomControlAttributesCS // // Description: This class provides a custom control with attributes to // provide the ability to alter the control programmically. // //**************************************************************************** using System; using System.Drawing; using System.Web; using System.Web.UI; namespace ASPNetCookbook.CSExamples { public class CH05CustomControlAttributesCS : Control {  // private copies of attribute data   private String mLabelText = "Label: ";   private Color mTextColor = Color.Black;   private int mTextboxWidth = 3;  //************************************************************************ // // ROUTINE: labelText // // DESCRIPTION: This property provides the ability to set the text // of the label in the control //------------------------------------------------------------------------  public String labelText   {   get   {   return(mLabelText);   }   set   {   mLabelText = value;   }   } // labelText  //************************************************************************ // // ROUTINE: textColor // // DESCRIPTION: This property provides the ability to set the color // of the text in the control //------------------------------------------------------------------------  public Color textColor   {   get   {   return(mTextColor);   }   set   {   mTextColor = value;   }   } // textColor  //************************************************************************ // // ROUTINE: textboxWidth // // DESCRIPTION: This property provides the ability to set the width // of the textbox in the control //------------------------------------------------------------------------  public int textboxWidth   {   get   {   return(mTextboxWidth);   }   set   {   mTextboxWidth = value;   }   } // textboxWidth  //************************************************************************ // // ROUTINE: Render // // DESCRIPTION: This routine renders the HTML output of the control //------------------------------------------------------------------------ protected override void Render(HtmlTextWriter writer) { //output label  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( ); } // Render } // CH05CustomControlAttributesCS } 

Example 5-6. Using the custom control with attributes (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH05DisplayControlWithAttributesVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH05DisplayControlWithAttributesVB" %>  <%@ Register TagPrefix="ASPCookbook" Namespace="ASPNetCookbook.VBExamples"   Assembly="ASPNetCookbookVB" %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Display Custom Control With Attributes</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmCustomControl" method="post" runat="server"> <table width="100%" cellpadding ="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Custom Control With Attributes (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td>With Default Attributes:</td> </tr> <tr bgcolor ="#ffffcc"> <td align="center">  <ASPCookbook:CH05CustomControlAttributesVB   id="ccAttributes1" runat="server" />  </td> </tr> <tr> <td><br />With Modified Attributes:</td> </tr> <tr bgcolor="#ffffcc"> <td align="center">  <ASPCookbook:CH05CustomControlAttributesVB   id="ccAttributes2" runat="server"   labelText = "Enter Age: "   textColor="#FF0000"   textboxWidth="10" />  </td> </tr> <tr> <td align="center"> <br> <asp:ImageButton ID="btnSubmit" Runat="server" ImageUrl="images/ buttons /button_submit.gif" /> </td> </tr> </table> </form> </body> </html> 



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

Similar book on Amazon

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