views:

376

answers:

4

Hi,

I have a onclick event that is like:

public void OnMyButton_Click(object sender, EventArgs e)

How can I call this from within pageload?

+5  A: 

Just call the method directly.

OnMyButton_Click(this, EventArgs.Empty);

Of course, if you find yourself programmatically triggering UI events, you may want to reconsider the structure of your page.

Dan Herbert
A: 
OnMyButton_Click(this.OnMyButton, null);
ChaosPandion
+6  A: 

Event handlers are just normal methods - you can call them from anywhere within the class they're defined in - so Dan's answer is technically correct, although I feel he leaves out a bit of best-practice advice.

Instead of calling your event handler from your load event, you should move the code in your event handler into another method, and then call that method from within both your click event handler, and your page load method.

Erik Forbes
+4  A: 

Refactor the code from inside the click event handler to a separate method and call the new method.

benPearce
ideally the logic shoudl be in a business layer, with the web page only handeling UI.
David Basarab
That may be the case - although I wouldn't give such advice given the information we have. The project in question may not be complex enough to warrant a separate business layer, and adding one to such a project would be a hinderance rather than a benefit.
Erik Forbes