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:

2 Responses to “Validation of a NumericUpDown control”

  1. Asadullah

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

  2. Seb Wills

    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.


Leave a Reply