如何在动态按钮上创建动态按钮单击事件 - VB.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21642678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i create dynamic button click event on dynamic button - VB.net
提问by Amarnath Balasubramanian
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?
我正在动态地在页面上创建一个按钮。现在我想在那个按钮上使用按钮点击事件。我怎样才能在 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
Multiple controls with the same ID were found
What is wrong with this code..!!
这段代码有什么问题..!!
回答by Fabio
After creating a dynamic button "subscribe" your eventhandler btnCode_Clickto event of the button:
创建动态按钮后,“订阅”您的事件处理程序btnCode_Click到按钮的事件:
AddHandler btnCode.Click, AddressOf btnCode_Click
Then EventHandlermust be at least Protected, but your is Private- it cannot be accessed then
那么EventHandler至少必须是Protected,但你是Private-它不能被访问

