6.8 Restrict a Text Box to Numeric Input


Problem

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

Solution

Add an event handler for the TextBox.KeyPress event. In the event handler, 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 text box because it provides a KeyPress event that occurs after the keystroke has been received but before it's 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 corresponds to a number (0 through 9) or a special control key (such as delete or the arrow keys). The keystroke character is provided to the KeyPress event through the KeyPressEventArgs.KeyChar property. You can use two static methods of the System.Char class IsDigit and IsControl to quickly test the character.

Here's the event handler you would use to prevent non-numeric input:

 private void textBox1_KeyPress(object sender,    System.Windows.Forms.KeyPressEventArgs e) {     if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar)) {         e.Handled = true;     } } 

Notice that this code rejects the decimal separator. If you need to allow this character (for example, to permit the user to enter a fractional currency amount), you'll have to modify the code slightly, as shown here:

 // Get the decimal separator character on this platform // (typically a "." for US-English). string decimalString =   Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator; char decimalChar = Convert.ToChar(decimalString); if (Char.IsDigit(e.KeyChar)  Char.IsControl(e.KeyChar)) {} else if (e.KeyChar == '.' && textBox1.Text.IndexOf(".") == -1) {} else {     e.Handled = true; } 

This code allows only a single decimal point, but it makes no restriction about how many significant digits can be used. It also doesn't allow the entry of negative numbers . (You could change this behavior by allowing the minus sign (-) provided it's the first character.) Remember that this code also assumes you have imported the System.Threading namespace.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net