Dynamic created Buttons VB.Net with Loop

╄→尐↘猪︶ㄣ 提交于 2019-12-02 13:25:01

问题


I have a very strange Problem with dynamic created Buttons in VB.NET: The Click Event is not fired when creating them in a Loop. Here is my code:

    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

This one doesn't work (only the PageLoad is fired, not the Click Event), but when i type

    Dim b14 As New Button
    b14.Text = "Test"
    b14.id = "asdf"
    AddHandler b14.Click, AddressOf updateFunc
    Panel1.Controls.Add(b14)

it works fine and the Event is fired.

The Header of the Function updateFunc is the following:

Protected Sub updateFunc(ByVal sender As Object, ByVal e As System.EventArgs)

Any ideas why it doesn't work with the Loop? Thanks for answers!


回答1:


Do you include IsPostBack checking? I assume you did. Try create the control outside.

 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



回答2:


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

use this it will work



来源:https://stackoverflow.com/questions/24604297/dynamic-created-buttons-vb-net-with-loop

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