6.5. Customizing an ASP.NET TextBox Server Control
Problem
You want to customize an ASP.NET TextBox
server control to allow only numeric input.
Solution
Create a custom control that inherits from the ASP.NET text box control and add code to emit client-side script that limits the input to only numeric values.
Use the .NET language of your choice to:
Create a class that inherits from the
TextBox
class in theSystem.Web.UI.WebControls
namespace.Override the
OnPreRender
method to have it generate the requisite client-side script.Override the
AddAttributesToRender
if you need to add an attribute to the rendered control.
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.
Examples 6-20 and 6-21 show the VB and C# class files for an example custom control we have written to illustrate our approach. This custom control emits client-side script that checks key presses and allows only numeric keys to be entered into a text box. Example 6-22 shows how to use the custom control in an ASP.NET page.
Discussion
Extending an existing ASP.NET server control is an easy way to create the functionality you need for an application. By inheriting your custom controls from existing controls, you only have to write the code you need to add your special functionality.
To illustrate this approach, we’ve implemented a text box control that allows only numeric input, a common project requirement. Why is it necessary to ...
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.