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!

1
  • Is this Windows Forms or Web Forms? Commented Jul 7, 2014 at 7:08

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

No, I have no IsPostBack in the whole Page. And the two codesnips are just next to each other without any code betweeen.
When do your create your controls? All dynamic created controls will be lost after a postback unless you recreate them. Check this out forums.asp.net/t/…
Wow you are correct! Thanks for the answer! Think that will help me!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.