Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling click event of a button serverside

Tags:

c#

asp.net

How can I click or load the click() event of a button in codebehind?
I already tried

      btn.Click();

but this gives an error. I am using ASP.NET

like image 649
code Avatar asked Jul 08 '10 11:07

code


People also ask

How do you call a button click event in code behind?

Button event is always trigger when you click the button but if you want to raise your button click event manually from code then you can use Button. PerformClick() from your code. Suppose on click of your Button1 you want to trigger Button2 click event then Please refer this[^] MSDN example.

Is button click an event?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.


4 Answers

I will assume that you have a button called Button1 and that you have double clicked it to create an event handler.

To simulate the button click in code, you simply call the event handler:

Button1_Click(object sender, EventArgs e).

e.g. in your Page Load Event

protected void Page_Load(object sender, EventArgs e)
{
    //This simulates the button click from within your code.
    Button1_Click(Button1, EventArgs.Empty);
}

protected void Button1_Click(object sender, EventArgs e)
{
    //Do some stuff in the button click event handler.
}
like image 180
I_LOVE_MONEY Avatar answered Sep 21 '22 03:09

I_LOVE_MONEY


If you don't need the context provided by the sender and eventargs then you can just refactor to create a method (eg DoStuff()) and make your event handler just call that. Then when you want to call the same functionality from elsewhere you can just call DoStuff(). It really depends on whether you want to actually simulate a click or not. If you want to simulate a click then other methods are better.

like image 21
Chris Avatar answered Sep 23 '22 03:09

Chris


Do you wish to call all the event handlers attached to the button, or just one?

If just one, call the handler:

 btn.btn_Click(btn, new EventArgs());

If all of them, trigger the event:

 var tmpEvent = btn.Click;
 if (tmpEvent != null)
      tmpEvent(btn, new EventArgs());
like image 38
James Curran Avatar answered Sep 21 '22 03:09

James Curran


Try this:

YourButton_Click(sender, e);
like image 21
user8097727 Avatar answered Sep 21 '22 03:09

user8097727