Hi

I've got a datagrid that I'm populating and depending on the data returned depends on what button I add. That all works fine until I click on the button and it posts the page and loses everything. Basically I can't get the button to fire.

Please help!
Lbob
This is my code

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
            bindDG()
End If
End Sub

Private Sub dg_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dg.ItemDataBound
If e.Item.ItemType = ListItemType.Item  Then
Dim btn As Button
btn = New Button
btn.Text = "Click Me"
btn.ID = e.Item.Cells(i).Text

AddHandler btn.Click, AddressOf btn_Click
e.Item.Cells(i).Controls.Add(btn)
end if
End Sub

Protected Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Select Case CType(sender, Button).Text
Case "Click Me"
trace.write("Hello")
End Select

because you are dynamically creating buttons they are not retaining state on postback and therefore wont fire the event assigned to them. You need to re-instantiate each dynamic control individually. E.g. when creating each control assign it an ID and save this to the viewstate. Then on page load loop through viewstate to find you controls and rebuild them. Some good examples are here

or you could use the "ItemCommand" event of the datagrid. This will fire if you set a commandname to your buttons when you create them and you wont need to retain state as above (Which can be messy if not implemented properly).

This article has been dead for over six months. Start a new discussion instead.