2

I have a button with OnClick=Button_Click. I want to call Button_Click from another function but the problem is that I need to give it:

(object sender, EventArgs e)

What should I enter for those parameters? Is there any way around it?

Or Betzalel
  • 2,427
  • 11
  • 47
  • 70
  • You talking about javascript or ASP.Net C# because OnClick event is for client side script not server side – Shekhar_Pro Feb 27 '11 at 00:17
  • I think he talks about server click event which is attached to button. You can easily determine by underscore convention – nemke Feb 27 '11 at 00:40

3 Answers3

8

You could do this

 Button_Click(null,EventArgs.Empty);

although I agree that it's better to extract function that could be called from anywhere.

For example if you have

protected void Button_Click(object sender, EventArgs e)
{
  //some list of code      
}

this code should be put in some new method and then called from Button_Click or any other method

private void ExtractedMethod()
{ 
 //some list of code
}

 protected void Button_Click(object sender, EventArgs e)
 {
  ExtractedMethod();    
 }

I recommend you to read a book Refactoring: Improving the Design of Existing Code by Martin Fowler. It's a must on a shelf. You will come back to that book from time to time, it's timeless.

nemke
  • 2,440
  • 3
  • 37
  • 57
1

Alternatively, if the action is done primarily by the button, or to avoid extra methods, as of .Net 4.0, there is a function called .PerformClick(). So

Button.PerformClick();

Would execute the button click from inside the code.

aklag
  • 11
  • 1
0

Extract the functionality that you have within the "onclick" into another function. You can then call it from anywhere, including the onClick.

Nasir
  • 10,935
  • 8
  • 31
  • 39