无法在VB.Net ASP.Net中动态创建的按钮上触发Click事件

时间:2016-10-21 08:36:04

标签: asp.net vb.net

我在Page_PreRender函数中创建一个代码来动态创建一些标签和按钮:

Dim btnExcludeDr As New Button()
btnExcludeDr.ID = "btnExcludeDr"
btnExcludeDr.Text = "Rate Driver"
form1.Controls.Add(btnExcludeDr)
AddHandler btnExcludeDr.Click, AddressOf Me.cmdExcludeDrv_Click

每个btnExcludeDr按钮必须触发的事件是:

Protected Sub cmdExcludeDrv_Click(ByVal sender As Object, ByVal e As System.EventArgs)
   MsgBox("hello")
End Sub

但事件并未解雇。你有什么解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:1)

创建动态控件的最佳位置是页面代码隐藏类提供的Page_Init函数。

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
    Dim btnExcludeDr As New Button()
    btnExcludeDr.ID = "btnExcludeDr"
    btnExcludeDr.Text = "Rate Driver"
    form1.Controls.Add(btnExcludeDr)
    AddHandler btnExcludeDr.Click, AddressOf Me.cmdExcludeDrv_Click
End Sub


Protected Sub cmdExcludeDrv_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    MsgBox("hello")
End Sub