Alex Rivera | Logout

How to find out if the "TextChanged" event is fired if user is typing into a textbox or myTextBox.Text is called programmatically

Asked 2012-03-09T15:38:43.900
8

Is there a way to find out if the "TextChanged" event is fired because

  1. the user is typing into a textbox or
  2. the programmer called myTextBox.Text = "something"?

Just to give you some color on this, I don't want to react when the user is typing each letter into the textbox so I am using the "Validated" event to catch when the user is done so I can react. The problem is I don't have a way to catch when the programmer does "myTextbox.Text = "something". The only way I know to catch changes there is to use TextChanged but then I don't want to be reacting when the user is typing each letter into the textbox. Any suggestions?

Edit
Report

1 Answer

6

I will guess that you're creaing a UserControl that other developers will use, thus "end-user" programmers may set the text programmatically. I think the simplest thing would be to follow @jzworkman's suggestion and make a class that overrides the Text property setter. As @vulkanino notes, you should probably raise and catch the Validating event, though.

public class TextBoxPlus : TextBox {
    public event CancelEventHandler ProgrammerChangedText;
    protected void OnProgrammerChangedText(CancelEventArgs e) {
        CancelEventHandler handler = ProgrammerChangedText;
        if (handler != null) { handler(this, e); }
    }

    public override string Text {
        get {
            return base.Text;
        }
        set {
            string oldtext = base.Text;
            base.Text = value;
            CancelEventArgs e = new CancelEventArgs();
            OnProgrammerChangedText(e);
            if (e.Cancel) base.Text = oldtext;
        }
    }
}

In your source, add the same handler to both the Validating and ProgrammerChangedText events:

// Somewhere...
textBoxPlus1.Validating += textBoxPlus1_Validating;
textBoxPlus1.ProgrammerChangedText += textBoxPlus1_Validating;

void textBoxPlus1_Validating(object sender, CancelEventArgs e) {
    decimal d;
    if (!Decimal.TryParse(textBoxPlus1.Text, out d)) {
        e.Cancel = true;
    }
}
answered 2012-03-09T16:09:17.323

Your Answer