Search code examples
c#winformsbuttonnumericnumericupdown

NumericUpDown custom increment using default Buttons


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.


Solution

  • 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);
        }
    }