Launch Javascript Events from .NET Datagrid Buttons

I sent out an email explaining how to add pushbuttons to a datagrid and capture the record ID of the button pushed. You can also launch client-side events based on a button push in a datagrid with the OnItemDataBind method. First add the method to your datagrid:

<asp:DataGrid id=”dgSearchResults” …. OnItemDataBound=”dgSearchResults_ItemDataBound” ….>

Then create your subroutine. In this case, the first cell contains the button we are targeting. We’re adding an onclick client side event that fires a javascript function to write a cookie. The cookie contains a field value (in this case objected) and expires in 14 days.

Sub dgSearchResults_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
First, make sure we’re NOT dealing with a Header or Footer row
If e.Item.ItemType ListItemType.Header And e.Item.ItemType ListItemType.Footer Then
Set you button as the first cell in the row
Dim idButton As Button = e.Item.Cells(0).Controls(0)
Add javascript onclick event to the button
idButton.Attributes(“onclick”) = “javascript:createCookie(‘objectid’,’” & _
DataBinder.Eval(e.Item.DataItem, “objectid”) & “‘,14);”
End If
End Sub

You can add any client-side event you want, including things like yes/no confirm dialogs or setting hidden form variable before postback.