Abdelouhab ELKADIRI Abdelouhab ELKADIRI - 1 month ago 6
Vb.net Question

Click event cannot be fired on buttons created dynamically in VB.Net ASP.Net

I'm creating a code in Page_PreRender function to dynamically creates some labels and buttons:

If (Not IsNothing(pol.PolicyInfo.DiscoveredDriverCollection)) Then
For j As Integer = 0 To pol.PolicyInfo.DiscoveredDriverCollection.Count - 1

'For Each discDriver As DiscoveredDriver In discDrivers
Dim lblDr As New Label()
lblDr.ID = "driver" & j
lblDr.Style("Position") = "Relative"
lblDr.Style("Top") = "10px"
lblDr.Width = 120
'lblDr.Style("display") = "inline-block"
'lblDr.Style("Left") = "10px"
'lblDr.Text = "Minor [" + discDriver.Sexe + "]"
lblDr.Text = "Minor [" + pol.PolicyInfo.DiscoveredDriverCollection(j).Sexe + "]"

Dim btnRateDr As New Button()
btnRateDr.ID = "rtDriver" & j
btnRateDr.Style("Position") = "Relative"
btnRateDr.Style("Top") = "10px"
btnRateDr.Style("Left") = "20px"
btnRateDr.Text = "Rate Driver"

Dim btnExcludeDr As New Button()
btnExcludeDr.ID = "exDriver" & j
btnExcludeDr.Style("Position") = "Relative"
btnExcludeDr.Style("Top") = "10px"
btnExcludeDr.Style("Left") = "45px"
btnExcludeDr.Text = "Exclude Driver"
btnExcludeDr.Attributes.Add("onclick", "return FindIdDriverControl('Edna');")

AddHandler btnExcludeDr.Click, AddressOf Me.cmdExcludeDrv_Click

driverList.Controls.Add(New LiteralControl("<br />"))

ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ShowDiscoveredDriversWarning", "ShowDiscoveredDriversWarning();", True)
End If

And the event which must be fired for each btnExcludeDr button is:

Protected Sub cmdExcludeDrv_Click(ByVal sender As Object, ByVal e As System.EventArgs)

Dim uidx As Int16 = hidDrvID.Value

Dim inputControl As rtr_driver_input = DriverControl(uidx)

Me.ExcludedDriver = inputControl.Driver 'Save to the viewstate

If inputControl.isEndorsement Then
inputControl.isRemoved = True
ExcludeButton(uidx).Visible = False
ResetButton(uidx).Text = "Undo"
'ResetButton(uidx).Visible = False

' decrease the control count
If CInt(lbl_ctrl_ct.Text) > min_num_Ctrl Then
lbl_ctrl_ct.Text = CInt(lbl_ctrl_ct.Text) - 1
End If
'Delete driver
End If

End Sub

But the event is not fired. Do you have any solution? thank you !


The best place to create your dynamic controls is in the Page_Init function that the page code-behind class provides.

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
    Dim btnExcludeDr As New Button()
    btnExcludeDr.ID = "btnExcludeDr"
    btnExcludeDr.Text = "Rate Driver"
    AddHandler btnExcludeDr.Click, AddressOf Me.cmdExcludeDrv_Click
End Sub

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