How can i create dynamic button click event on dynamic button - VB.net

牧云@^-^@ 提交于 2019-12-13 08:25:07

问题


I am creating a button on page dynamically. now i want to use button click event on that button. How can i do this in VB.net & asp.net?

My code:

Page Load:

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

            End Try
        End Sub

Load Controls

   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

Event Handler

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

Problem:

event handler doesn't arises..!! it throws an error

Multiple controls with the same ID were found

What is wrong with this code..!!


回答1:


After creating a dynamic button "subscribe" your eventhandler btnCode_Click to event of the button:

AddHandler btnCode.Click, AddressOf btnCode_Click

Then EventHandler must be at least Protected, but your is Private - it cannot be accessed then



来源:https://stackoverflow.com/questions/21642678/how-can-i-create-dynamic-button-click-event-on-dynamic-button-vb-net

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