开发者

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 开发者_如何学Cgives an error. I am using ASP.NET


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


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.


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


Try this:

YourButton_Click(sender, e);


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


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


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

You can use:

btn.PerformClick();


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


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

This works for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜