Search code examples
c#numericupdown

Numeric Up Down in c#


I write a program that has a "numericUpDow". My numericUpDown has the next configuration:

numericUpDown.Maximun = 5;
numericUpDown.Minimun = 0;

I wish I could select numbers from 0 to 5 minus 2, Is it possible?


Solution

  • Add form level variable:

    decimal oldValue = 0;
    

    Bind to ValueChanged event:

    numericUpDown.ValueChanged += numericUpDown_ValueChanged;
    

    numericUpDown_ValueChanged code:

    void numericUpDown_ValueChanged(object sender, EventArgs e)
    {
        NumericUpDown ctrl = sender as NumericUpDown;
        if (ctrl.Value == 2)
        {
            // bad, very very bad
            ctrl.Value = oldValue > 2 ? 1 : 3;
        }
        oldValue = ctrl.Value;
    }