Friday 18 January 2008

GridView Delete Button Adding Client-Side Confirmation

Let's say you have a GridView control containing a CommandField with the ShowDeleteButton attribute set to true like so:

<asp:CommandField ShowDeleteButton="True" />

When the user clicks on one of these delete buttons in the GridView the record is deleted so no problem right? WRONG! What happens if they clicked on the wrong button? There's no way currently of preventing that from happening.

So we add a Client-Side confirmation box asking the user to confirm the delete operation using the GridViews' RowDataBound event.


Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPending.RowDataBound

If e.Row.RowType = DataControlRowType.DataRow Then
Dim db As LinkButton = CType(e.Row.Cells(1).Controls(0), LinkButton)
db.OnClientClick = String.Format("return confirm('Please confirm you wish to delete this record ?');")
End If

End Sub

No comments: