tags:

views:

91

answers:

3

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?

+3  A: 

In general, you can't. The point of an event is to allow clients to subscribe and unsubscribe - it should be up to the publisher to raise the event. The fact that there even is a GetRaiseMethod is somewhat odd in my view - and unsupported in C# (you can only specify add/remove methods).

One alternative is to have a Dictionary<Button, EventHandler> or something similar, and register all the event handlers there too... but you might want to reflect upon why you want to force the click event to effectively fire in the first place. Perhaps there's a better design which would avoid this being an issue.

Jon Skeet
A: 

Jon Skeet is right; as far as the "contract" is concerned, there's an add and remove method, and that's about it. In effect, there is no guarantee that the event is implemented as a "field-like" event with a backing multicast delegate. There could be just about any backing data-structure to store each call-back (or none at all). Consequently, "raising an event" on an object is in general not well-defined.

Edit: Removed suggestion based on reflection. Go with @Hans Passant.

Ani
+3  A: 

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 :)

Hans Passant
+1: Oh, much better. Didn't know of this method.
Ani
I hadn't spotted it either. I think I'd still question the overall design in general though - it's at least worth giving it another pass to see if there's a cleaner approach.
Jon Skeet