动态创建按钮VB.Net与循环

时间:2014-07-07 06:33:43

标签: vb.net button event-handling

我对VB.NET中动态创建的按钮有一个非常奇怪的问题: 在循环中创建Click事件时不会触发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一起使用? 谢谢你的回答!

2 个答案:

答案 0 :(得分:1)

您是否包含 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

答案 1 :(得分:0)

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

使用它会起作用