C#: calling a button event handler method without actually clicking the button

橙三吉。 提交于 2019-11-28 22:32:30

问题


I have a button in my aspx file called btnTest. The .cs file has a function which is called when the button is clicked.

btnTest_Click(object sender, EventArgs e)

How can I call this function from within my code (i.e. without actually clicking the button)?


回答1:


btnTest_Click(null, null);

Provided that the method isn't using either of these parameters (it's very common not to.)

To be honest though this is icky. If you have code that needs to be called you should follow the following convention:

protected void btnTest_Click(object sender, EventArgs e)
{
   SomeSub();
}

protected void SomeOtherFunctionThatNeedsToCallTheCode()
{
   SomeSub();
}

protected void SomeSub()
{
   // ...
}



回答2:


Use

btnTest_Click( this, new EventArgs() );



回答3:


All above methods are not good because you might change event function name. The easiest is:

btnTest.PerfromClick();



回答4:


You can use reflection to Invoke the OnClick method which will fire the click event handlers.

I feel dirty posting this but it works...

MethodInfo clickMethodInfo = typeof(Button).GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);

clickMethodInfo.Invoke(buttonToInvoke, new object[] { EventArgs.Empty });



回答5:


If the method isn't using either sender or e you could call:

btnTest_Click(null, null);

What you probably should consider doing is extracting the code from within that method into its own method, which you could call from both the button click event handler, and any other places in code that the functionality is required.




回答6:


It's just a method on your form, you can call it just like any other method. You just have to create an EventArgs object to pass to it, (and pass it the handle of the button as sender)




回答7:


Simply call:

btnTest_Click(null, null);

Just make sure you aren't trying to use either of those params in the function.




回答8:


Inside first button event call second button(imagebutton) event:

imagebutton_Click((ImageButton)this.divXXX.FindControl("imagbutton"), EventArgs.Empty);

you can use the button state such as the imagebutton's commandArgument if you save something into it.




回答9:


btnTest_Click(new object(), EventArgs.Empty)




回答10:


You can call the btnTest_Click just like any other function.

The most basic form would be this:

btnTest_Click(this, null);



回答11:


btnSubmit_Click(btnSubmit,EventArgs.Empty);



回答12:


You have to pass parameter sender and e to call button event handler in .cs file

btnTest_Click(sender,e);



回答13:


btnTest.Click +=new EventHandler(btnTest_Click)


来源:https://stackoverflow.com/questions/2390439/c-calling-a-button-event-handler-method-without-actually-clicking-the-button

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