2

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!

deru
  • 460
  • 1
  • 4
  • 15

2 Answers2

4

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
HengChin
  • 583
  • 5
  • 16
  • No, I have no IsPostBack in the whole Page. And the two codesnips are just next to each other without any code betweeen. – deru Jul 07 '14 at 07:18
  • 1
    When do your create your controls? All dynamic created controls will be lost after a postback unless you recreate them. Check this out http://forums.asp.net/t/1186195.aspx?FAQ+Why+do+dynamic+controls+disappear+on+postback+and+not+raise+events+ – HengChin Jul 07 '14 at 07:20
  • Wow you are correct! Thanks for the answer! Think that will help me! – deru Jul 07 '14 at 07:35
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

use this it will work