David David - 1 year ago 224
C# Question

c# lock a windows forms control

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();
//allow the change

How can I do thins thing?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download