I set a minimum value of 1 and maximum of 10 for my "numericUpDown1". (C# Windows Form)
When I enter the value 0 manually from the keyboard, "numericUpDown1" automatically increases to 1, and when I enter a value greater than 10 manually from the keyboard, "numericUpDown1" automatically decreases to 10.
Is it possible for me to change these automatic returns? Ex: If I type 25, it will return 3 instead of 10.
Is there any option/property to change this?
I tried some options like "Validated", "Validating", "Leave" and "ValueChanged". But that didn't work.
When it is <=0 or >10, I wanted to return an error (messagebox) and automatically return the value of "numericUpDown1" to 1.
One way to do this is to handle the KeyDown
event. The approach I would personally use is to inherit NumericUpDown
and replace instances of it in the MainForm.Designer.cs file with my custom class. Now, if you set the value of Maximum
to 10 in the designer it will behave the way you describe.
class NumericUpDownEx : NumericUpDown
{
// Disable range checking in the base class.
public NumericUpDownEx()
{
base.Maximum = decimal.MaxValue;
base.Minimum = decimal.MinValue;
}
public new decimal Maximum { get; set; } = 100; // Keep default value the same
public new decimal Minimum { get; set; } = 0; // Keep default value the same
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
switch (e.KeyData)
{
case Keys.Enter:
e.Handled = e.SuppressKeyPress = true;
BeginInvoke((MethodInvoker)delegate
{
// In this case, Designer has set Min = 1, Max = 10
if (Value < Minimum || Value > Maximum)
{
var message = $"Error: '{Value}' is not legal.";
Value = 1;
MessageBox.Show(message);
Focus();
}
var length = Value.ToString().Length;
if (length > 0)
{
Select(0, length);
}
});
break;
}
}
.
.
.
}
You'll also want to do the same kind of action when the control loses focus.
.
.
.
/// <summary>
/// The Validating event doesn't always fire when we want it to,
/// especially if this is the only control. Do this instead;
/// </summary>
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
OnKeyDown(new KeyEventArgs(Keys.Enter));
}