-3

I'm programming a winforms app, and I have encountered a problem:

I have, for example, a numeric UpDown control, and when pressing the up/down button, I don't want it to change, but I want access to the new value, without changing the number on the control itself.

I need as well to be able to unlock it under some condition, so it would look like that:

 private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        if (!canChange)
        {
            int newValue = get_expected_new_value();
            doSomeStuff(newValue);
            //some_code_to_cancel_the_value_change;
        }
        else
        {
            //allow the change
            doSomeOtherStuff();
        }
    }

How can I do thins thing?

David
  • 39
  • 7
  • You could set `.Minimum` and `.Maximum` to the same value. That should prevent using either the buttons or text box to change the value. – HABO Nov 05 '16 at 20:57
  • isn't there any more gentle way of doing this? messing around with the minimum and maximum looks kinda awful and may lead to mistakes, plus I need to get the new expected value, minimum and maximum solution won't help me with this... – David Nov 05 '16 at 21:13

1 Answers1

0

You can use the Tag property of the numericUpDown1 to store the last value. Although it's not a particulary elegant solution.

Credit to: C# NumericUpDown.OnValueChanged, how it was changed?

In your case it can look something like this:

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            var o = (NumericUpDown) sender;
            int thisValue = (int) o.Value;
            int lastValue = (o.Tag == null) ? 0 : (int)o.Tag;
            o.Tag = thisValue;

            if (checkBox1.Checked) //some custom logic probably
            {
                //remove this event handler so it's not fired when you change the value in the code.
                o.ValueChanged -= numericUpDown1_ValueChanged;
                o.Value = lastValue;
                o.Tag = lastValue;
                //now add it back
                o.ValueChanged += numericUpDown1_ValueChanged;
            }
            //otherwise allow as normal
        }

Basicaly you store the last known good value in the Tag property. Then you check you condition and set the value back to the last good value.

Community
  • 1
  • 1
erikbozic
  • 1,605
  • 1
  • 16
  • 21