Reputation: 163
I have a NumericUpDown control with increment of 5
. Entering 1
using the keyboard is possible and shall always be possible.
But when I click the Up-button I want not to have a 6
but a 5
, always 5
, 10
, 15
...
How is this possible? In ValueChange
this is not possible, because I want the possibility to enter every single number by keyboard.
Upvotes: 2
Views: 1612
Reputation: 32248
You can derive a Custom Control from NumericUpDown, override both UpButton() and DownButton() to provide a custom logic to apply to the Increment
value.
Here, setting the Increment to 5
, the NumericUpDown Buttons (and the UP and DOWN keys, if InterceptArrowKeys is set to true
), will increment or decrement the Value by 5
.
If the User enters a different value with the keyboard, the value is accepted, unless it exceeds the Maximum
and Minimum
pre-sets. In this case, the Control is reset to the Maximum
or Minimum
value.
E.g., a User enters 16
: if the UpButton
is pressed, the value will be set to 20
, to 15
if the DownButton
is pressed instead.
In either case, the Value entered cannot exceed the upper and lower bounds.
Note that neither base.UpButton()
or base.DownButton()
are called, since these would adjust the Value to the Increment set using the standard method.
class NumericUpDpwnCustomIncrement : NumericUpDown
{
public NumericUpDpwnCustomIncrement() { }
public override void UpButton() =>
Value = Math.Min(Value + (Increment - (Value % Increment)), Maximum);
public override void DownButton() =>
Value = Math.Max(Value - (Value % Increment == 0 ? Increment : Value % Increment), Minimum);
protected override void OnValueChanged(EventArgs e)
{
base.OnValueChanged(e);
Value = Math.Max(Math.Min(Value, Maximum), Minimum);
}
}
Upvotes: 3
Reputation: 88
You can use NumbericUpDown Click event. It is called when up/down buttons are clicked.
private void OnClick(object sender, EventArgs e)
{
numericUpDown.Value -= numericUpDown.Value % 5;
}
Edit: since the event also gets called when the Textfield is clicked, I propose another solution.
You can override NumericUpDown methods UpButton and DownButton to trigger an event.
public class MyNumericUpDown : System.Windows.Forms.NumericUpDown
{
public event Action OnButtonPressed;
public override void UpButton()
{
base.UpButton();
OnButtonPressed?.Invoke();
}
public override void DownButton()
{
base.DownButton();
OnButtonPressed?.Invoke();
}
}
And inside YourForm.Designer.cs rewrite this.numericUpDown = new System.Windows.Forms.NumericUpDown();
to this.numericUpDown = new YourNamespace.MyNumericUpDown();
.
Then in your Form construcor add:
numericUpDown.OnButtonPressed += () => numericUpDown.Value -= numericUpDown.Value % 5;
Upvotes: 0