如何在动态按钮 - VB.net上创建动态按钮单击事件

时间:2014-02-08 06:13:26

标签: asp.net vb.net event-handling dynamic-controls

我正在动态地在页面上创建一个按钮。现在我想在该按钮上使用按钮点击事件。我怎么能在VB.net& asp.net?

我的代码:

页面加载:

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
            Try
               LoadControls()
             Catch ex As Exception

            End Try
        End Sub

加载控件

   Private Sub LoadControls()
    Try
       Dim ButtonTable As New HtmlTable
       Dim ButtonTableRow As New HtmlTableRow
       Dim ButtonTableCell As New HtmlTableCell
       Dim btnCode As New Button
           btnCode.ID = "btnCode"
           btnCode.Text = "btnCode"
           AddHandler btnCode.Click, AddressOf btnCode_Click
       ButtonTableCell.Controls.Add(btnCode)

       ButtonTableRow.Cells.Add(ButtonTableCell)
       ButtonTable.Rows.Add(ButtonTableRow)

       ControlsPlaceHolder.Controls.Add(ButtonTable)
 Catch ex As Exception

        End Try
    End Sub

事件处理程序

Private Sub btnCode_Click(sender As Object, e As EventArgs)

            Dim buttonId As New Button
            Try
                buttonId = DirectCast(sender, Button)

                // My execution
            Catch ex As Exception

            End Try
        End Sub

问题:

事件处理程序不会出现.. !!它会抛出错误

Multiple controls with the same ID were found

此代码有什么问题.. !!

1 个答案:

答案 0 :(得分:2)

创建动态按钮后,“订阅”您的事件处理程序btnCode_Click到按钮的事件:

AddHandler btnCode.Click, AddressOf btnCode_Click

然后EventHandler必须至少Protected,但您的Private - 无法访问