How to keep valid value in NumericUpDown instead assigning Maximum value?

Axm picture Axm · Aug 27, 2012 · Viewed 7.8k times · Source

Say I have NumericUpDown with Maximum = 99 and Minimum = -99 and initial value = 23. If user sets focus to this contol and inputs 1 (that would be 123 now) it changes it's value to 99. How do I keep 23 instead changing value to maximum allowed?

I tried to catch KeyDown and KeyPress, but value wasn't changed during this events. Also I tried to implement a workaround explained in this question, but not succeeded. Validating event occurs only on leaving control. I need to simply ignore user input if it's greater than Maximum or lesser than Minimum.

UPD. I'm using WinForms.

Answer

Thanatos picture Thanatos · Aug 27, 2012

Use an outside global property like private int iTextBox { get; set; } and use OnTextChange event to see if the number is bigger then 99 or smaller than -99.

OnTextChange:

{
       int newValue = int.Parse(textBox1.Text);
       if (newValue > Maximum)
              textBox1.Text = iTextBox;
       if (newValue < Minimum)
              textBox1.Text = iTextBox;

       iTextBox = int.Parse(textBox1.Text);
}