6.2. Creating a Custom Control with Attributes
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.
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:
Create a class that inherits from the
WebControlclass in the
Implement support for the HTML-style attributes by adding properties to the class.
TagKeyproperty to return the HTML tag to be used as a container for the control.
RenderContentsmethod 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 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 ...