如何添加事件处理程序,以动态控制在asp.net做回发?除了使用Javascript,还有可能吗?



如何添加事件处理程序的动态控制(一个按钮)在asp.net做回发?除了使用Javascript,这是可能的吗?

这是可能的。

因此,例如,在您的Page_Load中,您可以创建按钮。

这个例子是使用VB

必须在回发时重新创建,所以不要将其包装在If (Not isPostBack)中-否则将无法工作

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

然后在这里处理点击:

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

c#

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

和方法被调用

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

最新更新