6.1. Combining HTML Controls in a Single Custom Control
Problem
You want to create a custom control that combines two or more HTML controls.
Solution
Use the .NET language of your choice to:
Create a class that inherits from the
WebControl
class in theSystem.Web.UI.WebControls
namespace.Override the
Render
method to have it output the HTML controls you wish to include.(Optional) Use the
HtmlTextWriter
class to enhance your chances of writing well-formed HTML.
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.
Figure 6-1 shows the output of a custom control that combines a label and text box. Examples 6-1 and 6-2 show the VB and C# class files for the custom control. Example 6-3 shows how to use the custom control in an ASP.NET page.
Figure 6-1. Basic custom control output
Discussion
To create a custom control that combines the functionality of two or more HTML controls, you first create a class that inherits from the WebControl
class in System.Web.UI.WebControls
.
The only method of WebControl
required to output HTML is the Render
method. Render
is responsible for writing the HTML that will be rendered by the browser. To enhance your ability to write well-formed HTML, you can use other methods of the HtmlTextWriter
class along with the HtmlTextWriterAttribute
and HtmlTextWriterTag
enumerations. ...
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.