Home > Mobile >  c# increasing numericUpDown1 by increments of 25 and nothing else
c# increasing numericUpDown1 by increments of 25 and nothing else

Time:05-24

I am trying to set the numericUpDown1 so it will only increase by increments of 25. I only want the numbers to increase by 25 and not allow other things. so for example I want 25, 50 75, 100. I don't want any other number lets say 26,51,76,101 also is increments of 25 but I dont want that. I just want increments that are able to divide by 25 basically.

CodePudding user response:

Set your NumericUpDown's Increment property to 25, then double click on it in the designer and put a ValueChanged event handler that constrains the input to a multiple of 25:

    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        if (numericUpDown1.Value % 25 == 0) return;
        numericUpDown1.Value = Math.Round(numericUpDown1.Value / 25) * 25;
    }

The first line that checks % isn't strictly necessary and can be removed if you're happy to rely on an NUD not raising a ValueChanged event if it is set to the same value that is currently displaying.

The flow of the code is:

  • user types e.g. 7 into the box. ValueChanged fires.
  • 7% is not 0
  • the code rounds 7 down to 0 and sets the Value to 0.
  • ValueChanged fires again (because we just changed the value)
  • 0%0 is 0, the code returns from the second fire
  • the code returns from the first fire

If you remove the mod check the code still returns because:

  • user types e.g. 7 into the box. ValueChanged fires.
  • the code rounds 7 down to 0 and sets the Value to 0.
  • ValueChanged fires again (because we just changed the value)
  • the code rounds 0 down to 0 and sets the Value to 0
  • 0 is not a change in value so the event does not raise again
  • the code returns from the second fire
  • the code returns from the first fire

I've always preferred to put something in that I can see stops infinite firing if I change a control programmatically, but your preferences may differ

  •  Tags:  
  • c#
  • Related