1

I have a numericupdown control on a winform and I noticed while testing that not only you have the option of changing the value by pressing up and down key but also simply entering the values from your keyboard.

I don't want that. I only want the user to be able to change the numericupdown's value only by clicking the up and down buttons within the box.

So far I simply can't find a solution.

Does anyone know how to do this?

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
ThN
  • 3,235
  • 3
  • 57
  • 115

3 Answers3

3

To disable user from editing, set Readonly property to true.

updown.ReadOnly = true;

For more tailoring, you may refer this answer.

Community
  • 1
  • 1
Thinhbk
  • 2,194
  • 1
  • 23
  • 34
2

Sounds bad for user experience depending on the range of values you are allowing.

To do this you need to create a control with inherits from NumericUpDown and override the OnKeyPress/OnKeyDown methods.

Jamie
  • 4,670
  • 5
  • 35
  • 49
  • Jamie, it does sound bad. The real problem I am having is that I have a valuechanged event that needs to be fired every time the numericupdown value is changed, but it doesn't. It only fires when you use the up and down button not when you change its value by using keyboard. That's why I am looking for a way to make sure valuechanged event fires every time its value is changed. – ThN Nov 05 '12 at 15:52
  • As far as I am aware ValueChanged event fires when the control loses focus? Is that not sufficient? – Jamie Nov 05 '12 at 15:54
  • well, I just tested the control, works exactly like you described and it is not sufficient. From what you are telling me user has to click on some other control or the winform itself for the numericupdown control to loose its focus. So, valuechanged event can fire. What if they only want to change the value of a single numericupdown control on the winform and then click on OK button to close the winform. Plus, the OK button is Disabled and only becomes Enabled, when the valuechanged event fires. You see my delimma :) – ThN Nov 05 '12 at 16:05
  • 1
    You could inherit from the control and trigger the `ValueChanged` event and set the value in any of the OnKeyPress/OnKeyDown/OnKeyUp methods? – Jamie Nov 05 '12 at 16:15
  • Jamie, that's true, but I was looking for a simple solution, which wouldn't require me to write extra codes. – ThN Nov 05 '12 at 16:31
0

Using updown.ReadOnly = True; does not work for me. It seems to be a reoccuring bug. But catching any changes and then undo it does. For this bind the function updown_ValueChanged() to the updown.ValueChanged attribute.

    decimal spin = 1;
    private void updown_ValueChanged(object sender, EventArgs e)
    {
        if (updown.ReadOnly)
        {
            if (updown.Value != spin)
            {
                updown.Value = spin;
            }
        }
        else spin = updown.Value;
    }
PapaAtHome
  • 575
  • 8
  • 25