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 ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook 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.