C#: calling a button event handler method without actually clicking the button
开发者_运维百科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)?
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()
{
// ...
}
Use
btnTest_Click( this, new EventArgs() );
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 });
All above methods are not good because you might change event function name. The easiest is:
btnTest.PerfromClick();
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.
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
)
Simply call:
btnTest_Click(null, null);
Just make sure you aren't trying to use either of those params in the function.
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.
btnTest_Click(new object(), EventArgs.Empty)
You can call the btnTest_Click just like any other function.
The most basic form would be this:
btnTest_Click(this, null);
btnSubmit_Click(btnSubmit,EventArgs.Empty);
You have to pass parameter sender
and e
to call button event handler in .cs file
btnTest_Click(sender,e);
btnTest.Click +=new EventHandler(btnTest_Click)
精彩评论