Calling A Button OnClick from a function

爱⌒轻易说出口 提交于 2019-12-02 04:17:28

问题


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?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/5130584/calling-a-button-onclick-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!