I'm dynamically creating buttons for pagination that should be calling an event handler when clicked. The postback is happening, however it never hits the event sub. This is my button creation code (i = 0):
Do While (i < pages)
Dim btn As New Button With {
.Text = (i).ToString,
.CommandArgument = (i).ToString,
.ID = "btnGrdPage_" + (i).ToString
}
AddHandler btn.Click, AddressOf Me.btnGrdParticipantPage_Click
dvPageNumbers.Controls.Add(btn)
i += 1
Loop
The event I'm trying to get to on a click is as follows:
Protected Sub btnGrdParticipantPage_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim x = 1
...
End Sub
Where does that code live?
Remember that every postback creates (and then destroys) a brand new instance of the page class. You don't get to keep the same instance from post to post. This means the code to create the controls must re-run on every postback. Otherwise, those controls won't exist, and they'll just disappear after the next server event. Morever, this must happen very early in the page lifecycle... before ViewState is restored, because if the controls don't exist yet at this point, they can't get updated ViewState, and ViewState is how the page life cycle knows they need to raise the click event.
Page_Load()
is too late for this. Try usingPage_Init()
orPage_PreInit()
instead.