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.
Shouldn't this line:
ReplyDeleteelse if (e.KeyChar == '.' && textBox1.Text.IndexOf(".") == -1) {}
be:
else if (e.KeyChar == decimalChar && textBox1.Text.IndexOf(decimalChar) == -1) {}
?