在文本框中仅输入一位数字 [英] enter only single digit number in text box
本文介绍了在文本框中仅输入一位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的窗口应用程序中,我有很多文本框,我只想在其中输入一位数字值.就像我只输入2和3而不输入两位数23. >
In my window application i have many text box and i want to enter only single digit numeric value in it.Like i only enter 2 and 3 not enter two digit 23.How i do this can any one help.
if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", txt_Digit8.Text))
{
MessageBox.Show("Please enter only numbers.");
txt_Digit8.Text.Remove(txt_Digit8.Text.Length - 1);
}
我使用此代码,但不起作用.
我也想给范围像只接受0到5的数字.
I use this code but it not work.
Also i want to give range like only accept 0 to 5 number.
推荐答案
您可能需要 ^ ].
为什么不使用MaskedTextBox(掩码为#"),或者一个NumericUpDown,最小值为0,最大值为9?
无论哪种方式,用户都无法输入错误的值,因此无需验证.
Why not use a MaskedTextBox, with a Mask of "#", or a NumericUpDown, with a min on 0 and a max of 9?
Either way, the user can''t enter a wrong value, so no need to validate.
一个非常简单的代码:
使用以下事件和代码:
A very simple code:
use the following event and code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
textBox1.MaxLength = 1;
if (Char.IsNumber(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
这篇关于在文本框中仅输入一位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文