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:
Create a class that inherits from the
Control
class in theSystem.Web.UI
namespace.Implement support for the HTML-style attributes by adding properties to the class.
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:
Register the assembly containing the control.
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 ...
Get ASP.NET Cookbook 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.