I have a datagrid where I am programatically adding a linkbutton on ItemDataBound.
Protected Sub dgCounts_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgCounts.ItemDataBound
For i As Integer = 1 To (e.Item.Cells.Count - 1)
Dim lb As New LinkButton
lb.CommandArgument = aryDealers(i)
lb.Text = e.Item.Cells(i).Text
lb.CausesValidation = False
AddHandler lb.Click, AddressOf lb_Click
If e.Item.Cells(i).Text.Trim.Length > 0 Then
e.Item.Cells(i).Controls.Add(lb)
End If
Next
End Sub
Protected Sub lb_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lb As LinkButton = CType(sender, LinkButton)
Dim s As String = lb.CommandArgument
End Sub
The linkbutton is adding to the grid cells correctly, but when you the click event is not firing.
Thoughts?
Thanks!
You should not add controls dynamically in the DataGrid’s ItemDataBound Event (or GridView’s RowDataBound-Event).
ItemDataBoundis only triggered when you databind the DataGrid to it’s DataSource. If you’ve enabledViewStateand databind it only ifNot Page.IsPostback, the control would not be recreated on postbacks. Therefore no events are triggered.You should use ItemCreated instead(RowCreated in GridView) to create controls dynamically, because
ItemCreatedis called on every postback.