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”.
Category: Winforms | Tags: NumericUpDown
October 8th, 2008 at 11:57 pm
Hi,
I have a better way of doing this stuff
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;
}
March 30th, 2009 at 5:39 am
When I try this (the suggestion in the original post, not in the comment), the Text property seems to be already set to the text equivalent of Maximum by the time the Validating event occurs.