O'Reilly logo

ASP.NET Cookbook by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required