JohnM
JohnM

Reputation:

Looking for a simple C# numeric edit control

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.

Upvotes: 1

Views: 7940

Answers (5)

Ricardo Amores
Ricardo Amores

Reputation: 4687

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

Upvotes: 1

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

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.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 416059

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.

Upvotes: 0

paulwhit
paulwhit

Reputation: 8888

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

Upvotes: 0

anon
anon

Reputation:

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

Upvotes: 9

Related Questions