Sunday, November 18, 2007

Validation of a NumericUpDown control

The NumericUpDown control has a built-in validation:

  • Values smaller than the minimum are replaced by the minimum
  • Values larger than the maximum are replaced by the maximum

This may lead to a situation in which the user entered an invalid value and pressed the form's "OK" button, leading to saving of a value completely different than the one entered with no notification.
To prevent this, enter your own validation code into the validating event (using the "Text" property instead of "Value"), and if the validation fails set the e.Cancel argument to "true".

1 comment:

Unknown said...

Hi,

I have a better way of doing this stuff :D

handle KeyUp event of the numericUpDown control and use this code in the handler:

(NOTE: numDuration is the name of NumericUpDown instance)

int value;
if (!int.TryParse(numDuration.Text, out value))
{
numDuration.Value = numDuration.Minimum;
return;
}

if (value > numDuration.Maximum)
{
numDuration.Text = numDuration.Maximum.ToString();
e.Handled = true;
}
if (value < numDuration.Minimum)
{
numDuration.Text = numDuration.Minimum.ToString();
e.Handled = true;
}