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

时间:2021-09-18 20:56:41

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.

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

5 个解决方案

#1


8  

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

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

#2


1  

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.

我必须实现一个只接受数字,整数或实数的控制。我将控件构建为(read:derived from)TextBox控件的特化,并使用输入控件和常规expresión进行验证。添加范围验证非常简单。

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€

这是构建正则表达式的代码。 _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();
}

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.

正则表达式匹配任何数字(即任何带有数字字符的字符串),只有一个字符作为数字分隔,字符串开头的“+”或“ - ”可选字符。一旦你创建了正则表达式(当实例化控件时),你检查值是否正确覆盖OnValidating方法。 CheckValidNumber()只是将Regex应用于引入的文本。如果正则表达式匹配失败,则激活具有指定错误的错误提供程序(使用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);
   }
}

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

正如我所说,我还阻止用户在文本框中输入数据,而不是数字字符覆盖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);
}

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 ;))

优雅的触感:我检查每次用户释放密钥时该号码是否有效,以便用户可以在他/她键入时获得反馈。 (但请记住,您必须小心ValidationFail事件;))

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

#3


0  

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

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

#4


0  

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.

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

#5


0  

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

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

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

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

#1


8  

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

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

#2


1  

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.

我必须实现一个只接受数字,整数或实数的控制。我将控件构建为(read:derived from)TextBox控件的特化,并使用输入控件和常规expresión进行验证。添加范围验证非常简单。

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€

这是构建正则表达式的代码。 _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();
}

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.

正则表达式匹配任何数字(即任何带有数字字符的字符串),只有一个字符作为数字分隔,字符串开头的“+”或“ - ”可选字符。一旦你创建了正则表达式(当实例化控件时),你检查值是否正确覆盖OnValidating方法。 CheckValidNumber()只是将Regex应用于引入的文本。如果正则表达式匹配失败,则激活具有指定错误的错误提供程序(使用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);
   }
}

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

正如我所说,我还阻止用户在文本框中输入数据,而不是数字字符覆盖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);
}

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 ;))

优雅的触感:我检查每次用户释放密钥时该号码是否有效,以便用户可以在他/她键入时获得反馈。 (但请记住,您必须小心ValidationFail事件;))

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

#3


0  

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

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

#4


0  

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.

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

#5


0  

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

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

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

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