2

I am using the numericupdown control. When a value is assigned programmatically or user changes the value, the ValueChanged event is triggered.

I want the event to be triggered only when the user changes the values and not when I set the minimum and maximum values. How can it be done?

2 Answers 2

4

Building on TheVillageIdiot's answer... You could create a reusable subclass like:

public sealed class MyNumericUpDown : NumericUpDown {

    private bool suppress;

    protected override void OnValueChanged(EventArgs e) {
        if (!suppress) {
            base.OnValueChanged(e);
        }
    }

    public void SetRange(decimal min, decimal max) {
        suppress = true;
        try {
            Minimum = min;
            Maximum = max;
        }
        finally {
            suppress = false;
        }
    }

}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 I like the way you've moved the solution to a higher level of abstraction, and I'm thinking I might use a similar strategy in frequent occasions when I need to suppress recursion as two (or more) "synchronized" controls (like a TreeView and a Listview) update. Curiousity: if you care to add comments on why you made the class sealed, and why you used a try/catch block, that would be appreciated. Thanks !
I have a habit of sealing by default. In this case it doesn't matter. As for the try/finally - it's another habit to avoid a case where an exception exits the method leaving suppress set to true. Although in this case I don't know if an exception is possible, it's always good practice to ensure you set the flag back to the way it was.
+1 Thanks for your response, Josh. It took me less than five minutes to implement a "recursion proof" derived TreeView and ListView, with recursion controlled by a Public Property in each, and verify they worked as expected : the one downside : you gotta modify the Designer.cs file, or whip them up yourself, setting countless properties yourself, or, at least design with default controls, then rip settings out of the Designer.cs class and "transplant" them elsewhere, then go in and switch the declarations to your derived types. I'm generally against ever going near the Designer.cs file.
3

Try something like this:

var changeFromCode = false;

void abc()
{
   // This is where you change value in code.
   changeFromCode = true;
   ud1.Value = 15;
   changeFromCode = false;
}

// Sorry, I am not sure about handler signatures
void UpDownValueChanged(object sender, EventArgs e)
{
   if (changeFromCode)
       return;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.