Question

In my application I'd like to handle TextBox input in certain cases (some criteria is not filled, for example) and because KeyDown is useful only for keyboard input but not actual pasting from the clipboard (I wouldn't want to go through the trouble of doing that using Win32 calls anyway), I figured I'd just handle everything in my primary TextBox's TextChanged event. However, when there is something "wrong" and the user should not be able to type in it, if I am to call TextBox.Clear(); on it, TextChanged fires a second time, understandably, so the message gets displayed two times, as well. That's kind of annoying. Any way I can handle TextChanged only in this case? Sample code (inside txtMyText_TextChanged) :

if (txtMyOtherText.Text == string.Empty)
{
    MessageBox.Show("The other text field should not be empty.");

    txtMyText.Clear(); // This fires the TextChanged event a second time, which I don't want.

    return;
} 
Was it helpful?

Solution

What about to disconnect the event handler before the change and reconnect afterward?

if (txtMyOtherText.Text == string.Empty)
{
    MessageBox.Show("The other text field should not be empty.");
    txtMyText.TextChanged -= textMyText_TextChanged;
    txtMyText.Clear(); 
    txtMyText.TextChanged += textMyText_TextChanged;
    return;
} 

In more complex cases it is better to have a try/finally and reenable the TextChanged event in the finally part

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top