David David - 1 month ago 17
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();
doSomeStuff(newValue);
//some_code_to_cancel_the_value_change;
}
else
{
//allow the change
doSomeOtherStuff();
}
}


How can I do thins thing?

Answer

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.