Search code examples
asp.netvb.netdynamicaddhandler

Dynamic button - onclick just won't work


I have used this code in a few other projects, but this time I just can't get it to work.

I am attempting to track the click event of a button control, but it just isn't firing.

I have tried re-loading in the controls in the page.init (I had to change the ControlsToLoad from viewstate to session for this to even load the controls in again) but this did not work either.

This is a page I'm using for test purposes:

Inherits System.Web.UI.Page
Private ReadOnly Property ControlsToLoad() As List(Of String)
    Get
        If ViewState("ControlsToLoad") Is Nothing Then
            ViewState("ControlsToLoad") = New List(Of String)()
        End If
        Return DirectCast(ViewState("ControlsToLoad"), List(Of String))
    End Get
End Property




Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If ControlsToLoad.Count > 0 Then
        For Each sID As String In ControlsToLoad
            createControl(sID)
        Next
    End If

    If Not IsPostBack Then
        loadControls()
    End If

End Sub


Sub loadControls()

    createControl(123)
    ControlsToLoad.Add(123)

End Sub

Function createControl(ByVal sID As String)

    Dim oTile As New Button
    oTile.Text = Left(sID, 1)
    oTile.ID = sID
    oTile.Attributes("class") = "M_Tile_" & sID
    AddHandler oTile.Click, AddressOf click
    phMaze.Controls.Add(oTile)
    oTile.Dispose()
    oTile = Nothing


End Function
Protected Sub click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    Response.Write("Here")

End Sub

Any help is appreciated.

Thanks

Ben


Solution

  • For your dynamically added controls to participate in the page life cycle you need to create them in page PreInit event. see ASP.NET Page Life Cycle

    Update:

    You need to remove oTile.Dispose() as it destroys the object and removes the handler.