Search code examples
c#winforms

Force the `Click` event to fire - using reflection?


I have a bunch of buttons on my form, and at a certain point in my code I want to force the Click event to fire. I could do something like this:

if (myButton == btnFoo)
  btnFoo_Click(this, new EventArgs());
else if (myButton == btnBar)
  btnBar_Click(this, new EventArgs());
else if // blah blah
  ...

Obviously that's not ideal. This looks like a case for reflection, but I can't find the right method to do it, e.g.

var ei = myButton.GetType().GetEvent("Click"); // so far so good;
var mi = ei.GetRaiseMethod(); // always returns null - no good!

Documentation for GetRaiseMethod.

So how can I force the click code to run?


Solution

  • Use the PerformClick method:

     myButton.PerformClick();
    

    Maybe you have to cast to Button, I can't tell from your snippet. I'll assume you won't need to pursue the reflection code anymore :)