问题
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