I have a TextBox that has the TextChanged event set declaratively. In some cases, I want programmatically set this value. In these cases, I want to disable the TextChanged event until I'm done programmatically setting the value. Then, when I'm done, I want to restore the event handler to behave as it was.
For a single TextBox, I know I can accomplish this by doing the following:
myTextBox.TextChanged -= myTextBox_TextChanged;
myTextBox.Text = "[Some Value]";
myTextBox.TextChanged += myTextBox_TextChanged;
However, I want to write this functionality into a single method that can be accessed by several methods. For instance, I'm trying to do so something like the following
private void UpdateTextValue(TextBox textBox, string newValue)
{
object eventHandler = textBox.TextChanged;
textBox.TextChanged -= eventHandler;
textBox.Text = newValue;
textBox.TextChanged += eventHandler;
}
Unfortunately, this approach doesn't work. It won't even compile. Is there a way I can encapsulate the functionality I'm trying to accomplish in a method such as the one shown above? If so, how?
Thank you,