How to add event handlers to dynamic control in asp.net to do postback? Other than using Javascript, is it possible?

早过忘川 提交于 2020-01-23 17:23:29

问题


How to add event handlers to dynamic control( a button) in asp.net to do postback? Other than using Javascript, is it possible?


回答1:


Yes, this is possible.

So, for example, in your Page_Load you can create the button.

This example is using VB

This has to be recreated on postback, so DO NOT wrap it in an If (Not isPostBack) - otherwise it will not work

Dim btn As Button = New Button() With {.Text = "Click Me", .ID = "MyId"}
AddHandler btn.Click, AddressOf MyBtnClick ' This is the method to call

and then you handle the click in here:

Private Sub MyBtnClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim btn As Button = CType(sender, Button) ' Gets the button that fired the method
    ' Do your code here
End Sub

And here is the same in C#

Button btn = new Button {Text = "Click Me",ID = "MyId"};
btn.Click += new EventHanlder(MyBtnClick);

And Method being called

private void MyBtnClick(object sender, EventArgs e)
{
    Button btn = (Button)sender; // Gets the button that fired the method
    // Do your code here
}


来源:https://stackoverflow.com/questions/15690784/how-to-add-event-handlers-to-dynamic-control-in-asp-net-to-do-postback-other-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!