Calling a button click event on the server

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

  btn.Click(); 

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

+6
source share
9 answers

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

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

Button1_Click (object sender, EventArgs e).

eg. in your page loading 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. } 
+20
source share

If you don’t need the context provided by the sender and eventargs, you can simply reorganize it to create a method (e.g. DoStuff ()) and make an event handler just by calling it. Then, when you want to call the same functionality from other sources, you can simply call DoStuff (). It really depends on whether you really want to simulate a click or not. If you want to simulate a click, then it is better to use other methods.

+5
source share

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

If only one, call the handler:

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

If they all trigger an event:

  var tmpEvent = btn.Click; if (tmpEvent != null) tmpEvent(btn, new EventArgs()); 
+4
source share

Edit:

 protected void Page_Init(object sender, EventArgs e) { Button1.Click += new EventHandler(Button1_Click); } void Button1_Click(object sender, EventArgs e) { } 

on the .cs page

+1
source share

Just call the button press function. http://forums.asp.net/t/1178012.aspx

Instead of trying to trigger an event, just call the function that uses the event.

Example: btn.Click () calls btn_Click (object sender, EventArgs e)

therefore, you must call the btn_Click (btn, new EventArgs ()) function;

+1
source share

It was a long time ago, but here is my solution

You can use:

 btn.PerformClick(); 
+1
source share

Try the following:

 YourButton_Click(sender, e); 
+1
source share
 protected void Page_Load(object sender, EventArgs e) { functionName(); } protected void btn_Click(object sender, EventArgs e) { functionName(); } public void functionName() { //function code goes here, and call this function where ever you want } 

try this...

0
source share
  YourButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); 

This works for me.

0
source share

All Articles