我在VB.NET中动态创建按钮时遇到了一个非常奇怪的问题:在循环中创建它们时,不会触发Click事件。这是我的代码:
Panel1.Controls.Clear()
For i As Integer = 0 To 100 Step 1
Dim b15 As new Button
b15.Text = "Test3"
b15.id = "a" & i
AddHandler b15.Click, AddressOf updateFunc
Panel1.Controls.Add(b15)
Next
这个不起作用(只有PageLoad被触发,而不是Click事件(,但当我键入时
Dim b14 As New Button
b14.Text = "Test"
b14.id = "asdf"
AddHandler b14.Click, AddressOf updateFunc
Panel1.Controls.Add(b14)
它工作正常,事件被触发。
函数updateFunc的标题如下:
Protected Sub updateFunc(ByVal sender As Object, ByVal e As System.EventArgs)
有什么想法为什么它不适用于Loop吗?谢谢你的回答!
是否包含IsPostBack检查?我想是你干的。尝试在外部创建控件。
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'Do Something
Else
'Do Something else
End If
Panel1.Controls.Clear()
For i As Integer = 0 To 10 Step 1
Dim b15 As New Button
b15.Text = "Test3"
b15.ID = "a" & i
AddHandler b15.Click, AddressOf updateFunc
Panel1.Controls.Add(b15)
Next
End Sub
flpnlContent.Controls.Clear()
For i As Integer = 0 To 10
Dim b15 As New Button
b15.Text = "a" & i
b15.Name = "a" & i
AddHandler b15.Click, AddressOf btn_Click
flpnlContent.Controls.Add(b15)
Next
使用它将工作