What needs to be done to input only numbers into the textBox (VS C #)?
|
5 answers
private void tb_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } } |
For the possibility of entering the decimal separator. Immediately change to the correct system.
private void e_sum_KeyPress(object sender, KeyPressEventArgs e) { if ( !char.IsControl(e.KeyChar)) { //разделитель еще не стоит if (((e.KeyChar == '.') || (e.KeyChar == ',')) && (e_sum.Text.IndexOf(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]) == -1)) e.KeyChar = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]; else if (!char.IsDigit(e.KeyChar)) e.Handled = true; } } |
If this is WinForms
private void tb_KeyPress(object sender, KeyPressEventArgs e) { if (!Regex.IsMatch(e.KeyChar.ToString(), "\\d+")) e.Handled = true; } where tb_KeyPress is the keypress event handler. The code filters all non-numeric presses.
- It is too hard to use regexps for a problem that is easier to solve. Sparrow cannon. - andreycha
|
private void tb_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar)) e.Handled = true; } |
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { //запрещаем вводить в textBox1, все кроме числовых значений char number = e.KeyChar; if (!Char.IsDigit(number)) { e.Handled = true; } } |
NumericUpDown. - AlexeyM