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

C#: calling a button event handler method 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 });