1

I have a method that I want to invoke both on the TextChanged and Validating events. The problem is that the e parameter of TextChanged is of type EventArgs while the e parameter of Validating is of type CancelEventArgs.

I could obviously do something like this:

void TextBox_TextChanged(object sender, EventArgs e) => Method();
void TextBox_Validating(object sender, CancelEventArgs e) => Method();

but I wonder if there is an option to make both events to have the same event handler.

Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • 1
    Just use `void MyHandlerName(object sender, EventArgs e)` - it is valid for both events. – Evk Nov 11 '17 at 19:25
  • But why would you want to do that? I would have different handlers and then call common code from both of them. – CodingYoshi Nov 11 '17 at 19:27
  • @Evk - Thanks. I have tried but in the "Events" tab of the "Properties" panel, I don't see the method. – Michael Haddad Nov 11 '17 at 19:27
  • Well don't know anything about that panel, but I'm quite sure handler with this signature is valid for both events (because CancelEventArgs inherit from EventArgs), try to do that in code for example (`textBox.Validating += MyHandler`) – Evk Nov 11 '17 at 19:29
  • @CodingYoshi - the specific reason is that the method I want to invoke validates the `TextBox`, and I want it to be validated both when the user types and when it loses its focus. – Michael Haddad Nov 11 '17 at 19:29
  • @Evk it seems to work. But mister_giga wrote it as an answer so I will accept. Thanks. – Michael Haddad Nov 11 '17 at 19:32
  • @sipo so take the code and place it in a common method. Call it from both handlers. – CodingYoshi Nov 11 '17 at 19:32
  • @CodingYoshi - that is the hassle I want to avoid. – Michael Haddad Nov 11 '17 at 19:34

1 Answers1

3

Since EventArgs is base for CancelEventArgs, you can use (object sender, EventArgs e) for both events. On properties window you may not see proper event name because you use base class so you can write name there manually

mister_giga
  • 560
  • 1
  • 15
  • 37