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

我的梦境 提交于 2019-11-30 01:48:18
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() );
majkinetor

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

btnTest.PerfromClick();

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 });

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)

Aaron

Simply call:

btnTest_Click(null, null);

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

Amy

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);
Rijwan
btnSubmit_Click(btnSubmit,EventArgs.Empty);
user8972244

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