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.4. 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 text box control, and then add code to emit client-side script that limits the input to only numeric values.

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. Override the OnPreRender method to have it generate the requisite client-side script.

  3. Override the AddAttributesToRender if you need to add an attribute to the rendered control.

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.

Example 5-15 and Example 5-16 show the VB and C# class files for an example custom control that 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 5-17 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 are left to write only 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 ...

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