您好,抱歉,这是一个简单的问题,但如果有人可以指导我使用代码,我将不胜感激。我的 Winform 中有 50 个文本框。所有都应该只允许数字值,并且也只允许在 1-100 之间。我应该如何确保这种验证?
我的想法是在按键事件中使用 e.Keychar 使用 Ascii 值来限制用户只能输入数字。另外,也许我可以确保在属性中设置此验证?但我不知道我是否正确,也不知道正确的代码。请帮助我。
最佳答案
使用NumericUpDown
而不是带有验证的普通 TextBox
框。
A NumericUpDown control contains a single numeric value that can be incremented or decremented by clicking the up or down buttons of the control. The user can also enter in a value, unless the ReadOnly property is set to true.
您可以指定最小和最大数字,它将允许用户输入 1 到 100 之间的数字,并允许他们使用向上和向下按钮。
编辑:如果您想通过代码来完成此操作,那么您可以尝试在 TextBox
的 KeyPress
事件中进行类似操作:
private void yourTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
可以改进上面的内容以访问十进制数的 .
,但我想您已经明白了。
关于c# - C# Winforms 中的文本框验证 - 应仅允许 1-100 之间的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861315/