O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

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

Restrict a Text Box to Numeric Input

Problem

You need to create a text box that will reject only all non-numeric keystrokes.

Solution

Add an event handler for the TextBox.KeyPress event, and set the KeyPressEventArgs.Handled property to True to reject an invalid keystroke.

Discussion

The best way to correct invalid input is to prevent it from being entered in the first place. This approach is easy to implement with the .NET text box because it provides a KeyPress event that occurs after the keystroke has been received but before it has been displayed. You can use the KeyPressEventArgs event parameter to effectively "cancel" an invalid keystroke by setting the Handled property to True.

To allow only numeric input, you must allow a keystroke only if it ...

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