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