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.
Ok, I found solution with this question help. I tried many combinations and found one that wasn't too complicated. I save old value on KeyDown event and check it on textBox.TextChanged
event. At that time value haven't changed yet. Now numericUpDown visually discards input that will be not in Minimum...Maximum range. Not user-friendly I think, there is some work to do.
public partial class Form1
{
private decimal _oldValue;
private TextBox textBox;
public Form1()
{
InitializeComponent();
textBox = (TextBox)numericUpDown.Controls[1];
textBox.TextChanged += TextBoxOnTextChanged;
}
private void TextBoxOnTextChanged(object sender, EventArgs eventArgs)
{
decimal newValue = Convert.ToDecimal(((TextBox) sender).Text);
if (newValue > numericUpDown.Maximum || newValue < numericUpDown.Minimum)
((TextBox) sender).Text = _oldValue.ToString();
}
private void numericUpDown_KeyDown(object sender, KeyEventArgs e)
{
_oldValue = ((NumericUpDownCustom) sender).Value;
}
}