寻找一个简单的C#数字编辑控件

发布于 2024-07-05 12:43:46 字数 50 浏览 12 评论 0原文

我是一名 MFC 程序员,刚接触 C#,正在寻找一个允许数字输入和范围验证的简单控件。

I am a MFC programmer who is new to C# and am looking for a simple control that will allow number entry and range validation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

花期渐远 2024-07-12 12:43:46

查看“NumericUpDown”控件。 它具有范围验证,输入始终是数字,并且具有那些漂亮的递增/递减按钮。

Look at the "NumericUpDown" control. It has range validation, the input will always be numeric, and it has those nifty increment/decrement buttons.

半仙 2024-07-12 12:43:46

我必须实现一个只接受数字、整数或实数的控件。
我将控件构建为 TextBox 控件的专业化(读:派生自),并使用输入控件和正则表达式进行验证。
添加范围验证非常容易。

这是构建正则表达式的代码。 _numericSeparation 是一个字符串,其中的字符被接受为十进制逗号值
(例如,'.' 或 ',': $10.50 10,50€

private string ComputeRegexPattern()
{
   StringBuilder builder = new StringBuilder();
   if (this._forcePositives)
   {
       builder.Append("([+]|[-])?");
   }
   builder.Append(@"[\d]*((");
   if (!this._useIntegers)
   {
       for (int i = 0; i < this._numericSeparator.Length; i++)
       {
           builder.Append("[").Append(this._numericSeparator[i]).Append("]");
           if ((this._numericSeparator.Length > 0) && (i != (this._numericSeparator.Length - 1)))
           {
               builder.Append("|");
           }
       }
   }
   builder.Append(@")[\d]*)?");
   return builder.ToString();
}

正则表达式匹配仅用一个字符作为数字分隔符的任何数字(即任何带有数字字符的字符串)以及 '+' 或 ' -' 字符串开头的可选字符。
创建正则表达式(实例化控件时)后,您可以覆盖 OnValidating 方法来检查值是否正确。
CheckValidNumber() 只是将正则表达式应用于引入的文本。 如果正则表达式匹配失败,则激活具有指定错误的错误提供程序(使用 ValidationError 公共属性设置)并引发 ValidationError 事件。
在这里您可以进行验证以了解该数字是否在要求的范围内。

private bool CheckValidNumber()
{
   if (Regex.Match(this.Text, this.RegexPattern).Value != this.Text)
   {
       this._errorProvider.SetError(this, this.ValidationError);
       return false;
   }
   this._errorProvider.Clear();
   return true;
}

protected override void OnValidating(CancelEventArgs e)
{
   bool flag = this.CheckValidNumber();
   if (!flag)
   {
      e.Cancel = true;
      this.Text = "0";
   }
   base.OnValidating(e);
   if (!flag)
   {
      this.ValidationFail(this, EventArgs.Empty);
   }
}

正如我所说,我还阻止用户在文本框中输入除数字字符之外的数据,从而覆盖 OnKeyPress 方法:

protected override void OnKeyPress(KeyPressEventArgs e)
{
    if ((!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) && (!this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._numericSeparator.Contains(e.KeyChar.ToString())))
    {
        e.Handled = true;
    }
    if (this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._forcePositives)
    {
        e.Handled = true;
    }
    if (this._numericSeparator.Contains(e.KeyChar.ToString()) && this._useIntegers)
    {
        e.Handled = true;
    }
    base.OnKeyPress(e);
}

优雅的风格:每次用户释放按键时,我都会检查数字是否有效,以便用户可以获得反馈:他/她打字。 (但请记住,您必须小心 ValidationFail 事件;))

protected override void OnKeyUp(KeyEventArgs e)
{
    this.CheckValidNumber();
    base.OnKeyUp(e);
}

I had to implement a Control which only accepted numbers, integers or reals.
I build the control as a specialization of (read: derived from) TextBox control, and using input control and a regular expresión for the validation.
Adding range validation is terribly easy.

This is the code for building the regex. _numericSeparation is a string with characters accepted as decimal comma values
(for example, a '.' or a ',': $10.50 10,50€

private string ComputeRegexPattern()
{
   StringBuilder builder = new StringBuilder();
   if (this._forcePositives)
   {
       builder.Append("([+]|[-])?");
   }
   builder.Append(@"[\d]*((");
   if (!this._useIntegers)
   {
       for (int i = 0; i < this._numericSeparator.Length; i++)
       {
           builder.Append("[").Append(this._numericSeparator[i]).Append("]");
           if ((this._numericSeparator.Length > 0) && (i != (this._numericSeparator.Length - 1)))
           {
               builder.Append("|");
           }
       }
   }
   builder.Append(@")[\d]*)?");
   return builder.ToString();
}

The regular expression matches any number (i.e. any string with numeric characters) with only one character as a numeric separation, and a '+' or a '-' optional character at the beginning of the string.
Once you create the regex (when instanciating the Control), you check if the value is correct overriding the OnValidating method.
CheckValidNumber() just applies the Regex to the introduced text. If the regex match fails, activates an error provider with an specified error (set with ValidationError public property) and raises a ValidationError event.
Here you could do the verification to know if the number is in the requiered range.

private bool CheckValidNumber()
{
   if (Regex.Match(this.Text, this.RegexPattern).Value != this.Text)
   {
       this._errorProvider.SetError(this, this.ValidationError);
       return false;
   }
   this._errorProvider.Clear();
   return true;
}

protected override void OnValidating(CancelEventArgs e)
{
   bool flag = this.CheckValidNumber();
   if (!flag)
   {
      e.Cancel = true;
      this.Text = "0";
   }
   base.OnValidating(e);
   if (!flag)
   {
      this.ValidationFail(this, EventArgs.Empty);
   }
}

As I said, i also prevent the user from input data in the text box other than numeric characteres overriding the OnKeyPress methdod:

protected override void OnKeyPress(KeyPressEventArgs e)
{
    if ((!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) && (!this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._numericSeparator.Contains(e.KeyChar.ToString())))
    {
        e.Handled = true;
    }
    if (this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._forcePositives)
    {
        e.Handled = true;
    }
    if (this._numericSeparator.Contains(e.KeyChar.ToString()) && this._useIntegers)
    {
        e.Handled = true;
    }
    base.OnKeyPress(e);
}

The elegant touch: I check if the number valid every time the user releases a key, so the user can get feedback as he/she types. (But remember that you must be carefull with the ValidationFail event ;))

protected override void OnKeyUp(KeyEventArgs e)
{
    this.CheckValidNumber();
    base.OnKeyUp(e);
}
小草泠泠 2024-07-12 12:43:46

您可以使用常规文本框和验证器控件来控制输入。

You can use a regular textbox and a Validator control to control input.

赠我空喜 2024-07-12 12:43:46

尝试使用错误提供程序控件来验证文本框。 您可以使用 int.TryParse() 或 double.TryParse() 检查它是否是数字,然后验证范围。

Try using an error provider control to validate the textbox. You can use int.TryParse() or double.TryParse() to check if it's numeric and then validate the range.

饮惑 2024-07-12 12:43:46

您可以使用RequiredFieldValidator 和CompareValidator 的组合(将运算符设置为DataTypeCheck,并将Type 设置为Integer),

如果您愿意,这将使用普通文本框获得它,否则上面的建议很好。

You can use a combination of the RequiredFieldValidator and CompareValidator (Set to DataTypeCheck for the operator and Type set to Integer)

That will get it with a normal textbox if you would like, otherwise the recommendation above is good.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文