6
votes

I have a NumericUpDown variable in my class. The minimum and maximum values are set as follows:

myNumericUpDown.Maximum = 9999;
myNumericUpDown.Minimum = 0;

This prevents the spin box from exceeding 9999 or going below 0.

The problem I am having is when the user types inside the text box they can type any arbitrary number greater than Maximum or less than Minimum.

Is there a property in the NumericUpDown class that controls the minimum and maximum values for the text box? Or do I have to write a callback procedure that checks for this condition?

1
maybe you could add the validation on the textbox: use a masked text box that allows you only enter numbers with maximum 4 digitsGonzalo.-
This would require that the NumericUpDown class has a property to get the text box. I will check that now.Jan Tacci
I dont see any method to get the text box. Maybe what I will do is just set the ReadOnly property to true forcing the user to use the spin control to enter the value.Jan Tacci
as far as I search, you will have to write a callback to check if the value is betweeh max and minGonzalo.-
This is standard behavior, you cannot know when the user is done typing. Until she presses the Tab key or clicks another control. At which point the Maximum is automatically applied.Hans Passant

1 Answers

3
votes

If you set the property in the properties pane in the forms design view it will handle this for you. If the user were to enter 12000 and you had a maximum of 9999, as soon as the control loses focus the control drops to its maximum value of 9999. It goes the same with a negative value. It would automatically go to 0 once the control loses focus.

If you didn't want a user to be able to enter more than 4 digits, then you could just watch the KeyDown Event.

    /// <summary>
    /// Checks for only up to 4 digits and no negatives
    /// in a Numeric Up/Down box
    /// </summary>
    private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
    {
        if (!(e.KeyData == Keys.Back || e.KeyData == Keys.Delete))
            if (numericUpDown1.Text.Length >= 4 || e.KeyValue == 109)
            {
                e.SuppressKeyPress = true;
                e.Handled = true;
            }
    }