Numericupdown mousewheel event increases decimal more than one increment

JonF picture JonF · Mar 8, 2011 · Viewed 9.6k times · Source

I'm trying to override the mousewheel control so that when the mouse wheel is moved up or down it only increases the value in the numericupdown field by 1. I believe it is currently using what is stored in the control panel and increasing/decreasing the value by 3 each time.

I'm using the following code. Even when numberOfTextLinesToMove is only 1 and I see that txtPrice.Value is getting populated as expected, something else is overwriting it because the value I set is not what is displayed in the numericupdown box

void txtPrice_MouseWheel(object sender, MouseEventArgs e)
        {
            int numberOfTextLinesToMove = e.Delta  / 120;
            if (numberOfTextLinesToMove > 0)
            {
                txtPrice.Value = txtPrice.Value + (txtPrice.Increment * numberOfTextLinesToMove);
            }
            else 
            {

                txtPrice.Value = txtPrice.Value - (txtPrice.Increment * numberOfTextLinesToMove);
            }

        }

Answer

Evan picture Evan · May 2, 2013

I recently had this problem, and got around it by changing the increment.

numericUpDown1.Increment = 1m / SystemInformation.MouseWheelScrollLines;

Edit: This is only a good solution if you intend to only use the mousewheel to change the value. To fix this for all situations, you have to override the class. Here's a simple version.

public class NumericUpDownFix : System.Windows.Forms.NumericUpDown
{
    protected override void OnMouseWheel(MouseEventArgs e)
    {
        HandledMouseEventArgs hme = e as HandledMouseEventArgs;
        if (hme != null)
            hme.Handled = true;

        if (e.Delta > 0)
            this.Value += this.Increment;
        else if (e.Delta < 0)
            this.Value -= this.Increment;
    }
}