0

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

Benjo
  • 5
  • 5
Benjo
  • 179
  • 1
  • 8
  • you need to add vb.net tags if you want help with this - however nothing glaring I can see - cant see where `phMaze` is defined so start there maybe? Add the vb tag you will get more help! – GrahamTheDev Apr 13 '14 at 10:38
  • Thanks for the reply Graham. The phMaze is a fixed placeholder on the page; nothing that should cause any issues. – Benjo Apr 13 '14 at 11:00

1 Answers1

1

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.

MK.
  • 5,139
  • 1
  • 22
  • 36
  • The ControlsToLoad.Count is always zero when in the Init or PreInit – Benjo Apr 14 '14 at 09:02
  • Thats improper use of viewstate and you should use another approach – MK. Apr 14 '14 at 09:06
  • As I mentioned in my original post, changing from viewstate to session variables allows me to put the code in the preinit or init, but the same problem remains with the onclick event. – Benjo Apr 14 '14 at 09:42
  • Remove oTile.Dispose() – MK. Apr 14 '14 at 09:45
  • Remove oTile.Dispose() worked thanks! Feel free to add as a separate answer so I can mark it up. – Benjo Apr 14 '14 at 10:24