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

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.