c# - C# Winforms 中的文本框验证 - 应仅允许 1-100 之间的数字

标签 c# .net winforms c#-4.0

您好,抱歉,这是一个简单的问题,但如果有人可以指导我使用代码,我将不胜感激。我的 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 之间的数字,并允许他们使用向上和向下按钮。

编辑:如果您想通过代码来完成此操作,那么您可以尝试在 TextBoxKeyPress 事件中进行类似操作:

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/

相关文章:

.net - 时间作为决定性值(value)

.NET:System.ComponentModel.DataAnnotations

.net - 如何在线程中打开表单并强制其保持打开状态

c# - 在 WINFORM 中,listView ColumnWidthChanging 事件未触发或替代以禁用调整列大小

c# - 从带格式的 datagridview 生成 Excel 的最快方法

c# - ICollection<T> 的简单现有实现

c# - 无法使用DataStax C# Drive将cassandra中的 "Set"转换为c#中的 "SortedSet"或 "HashSet"

c# - pinvoke 期间未将第二个值传递给 C++ 函数

c# - 情态形式消失之谜

c# - Windows服务的基本应用有哪些?