سؤال

I have a form with a System.Windows.Forms.NumericUpDown control.

Say that the range is from 0 to 100, and the current value (arrived at via the spinner) is 100. I can type in a number that is outside of the allowable range (say 567) but when I click OK on the form to reset the value, it just silently sets the out of range value to 100 and closes the form.

The customer wants an explicit message that the number is out of range. So, I looked at checking the NumericUpDown.Text property on the form close, but that property gives me back "100" not "567".

Where (or how) can I "catch" the fact that the text appearing in the control is "567"?

هل كانت مفيدة؟

المحلول

You can use the answer from this question to capture the invalid value by getting a reference to the TextBox inside the NumericUpDown and handling its Validating event. In your handler, the TextBox.Text property will have the invalid value to test against. Works for me in .NET 2.0 Winforms.

نصائح أخرى

You could try this, the only thing is that the value will still be reset to 100, but the user will still be notified of the out of range value:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            int val = Convert.ToInt32(((UpDownBase)numericUpDown1).Text);

            if (val > 100)
            {
                MessageBox.Show("The value " + ((UpDownBase)numericUpDown1).Text + 
                " is out of range", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                e.Cancel = true;
            }
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top