code
code

Reputation: 139

Calling click event of a button serverside

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

Upvotes: 13

Views: 82693

Answers (9)

user8097727
user8097727

Reputation: 21

Try this:

YourButton_Click(sender, e);

Upvotes: 2

Matt126
Matt126

Reputation: 997

It's been a long time ago, but here is my solution

You can use:

btn.PerformClick();

Upvotes: 1

P.G Wisgerhof
P.G Wisgerhof

Reputation: 762

 YourButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

This works for me.

Upvotes: 0

Tapan kumar
Tapan kumar

Reputation: 6999

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 one.......

Upvotes: 0

Gage
Gage

Reputation: 7503

Just call the buttons click function. http://forums.asp.net/t/1178012.aspx

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

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

so you should call the function btn_Click(btn,new EventArgs());

Upvotes: 1

I_LOVE_MONEY
I_LOVE_MONEY

Reputation: 329

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.
}

Upvotes: 28

anishMarokey
anishMarokey

Reputation: 11397

Edit try this:

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

 void Button1_Click(object sender, EventArgs e)
{
}

in the .cs page

Upvotes: 1

Chris
Chris

Reputation: 27599

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.

Upvotes: 5

James Curran
James Curran

Reputation: 103505

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

Upvotes: 4

Related Questions