Have you ever needed to raise a button-click event programmatically? I sure have. Sometimes you end up needing to programmatically simulate that a button was clicked by a user, but how do you accomplish this? Often, I just call the event handling method that is registered for the button-click event. And. most of the time this is acceptable. Or, sometimes I put the actual code I need executed in a common method, and have the button-click event method call the common method, and then I can also call the common method from whereever I need. However, there is a risk to these approaches. What if the button-click event had more than one method registered?
If that question confuses you, you should be aware of the multicast delegate. A multicast delegate allows more than one method to be registered with the delegate. Button-click events are such a delegate. This means it is possible to have more than one method get called when the user clicks a button.
For an example of why you might have more than one method mapped to an event, please read my blog post here.
The Problem
So, this takes us back to the original problem, how do you programmatically raise a button-click event?
The Solution
You can use the following C# code raise the event:
((IPostBackEventHandler)Button1).RaisePostBackEvent(null);
This code will raise the button-click event for Button1 just as though the user clicked the button. Since we are passing a null as the EventArgs for the event, the registered methods must not attempt to do anything with it. Or, you could create an EventArgs object and pass it.
There is at least one other approach using reflection, but I think the technique above is the cleaner way to do this. However, if you are interested, you can read more about this topic here:
http://forums.asp.net/1/1509200/ShowThread.aspx