C#: calling a button event handler method without

2019-02-02 00:12发布

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)?

13条回答
趁早两清
2楼-- · 2019-02-02 00:31

You can call the btnTest_Click just like any other function.

The most basic form would be this:

btnTest_Click(this, null);
查看更多
在下西门庆
3楼-- · 2019-02-02 00:31
btnTest.Click +=new EventHandler(btnTest_Click)
查看更多
萌系小妹纸
4楼-- · 2019-02-02 00:36

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

btnTest.PerfromClick();
查看更多
forever°为你锁心
5楼-- · 2019-02-02 00:38

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 });
查看更多
再贱就再见
6楼-- · 2019-02-02 00:40

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.

查看更多
家丑人穷心不美
7楼-- · 2019-02-02 00:42
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()
{
   // ...
}
查看更多
登录 后发表回答