Confirm delete for GridView's CommandField using JavaScript

Been a while since I have had to do this, and to describe my memory as “sieve-like” is probably being generous. After vainly looking for the non-existent OnClientClick property of the CommandField (still can’t quite believe they don’t have that), I tried to recall the best way of wiring this up.

One way is to use a use a TemplateField instead with an ImageButton control or similar and take advantage of its OnClientClick property. If you give it an appropriate CommandName (i.e. “delete”) the GridView will automatically fire the OnRowDeleting event if you have wired it up:

    <asp:ImageButton runat="server" ID="DeleteButton" 
      OnClientClick="if (!window.confirm('Are you sure you want to delete this item?')) return false;" />

Another option is to hook into the RowDataBound event in code behind to attach the required JavaScript to the button in the CommandField, as is suggested in one of Scott Mitchell’s great ASP.NET 2.0 data access tutorials (see Step 3):

protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType != DataControlRowType.DataRow) return;

int lastCellIndex = e.Row.Cells.Count - 1;
ImageButton deleteButton = (ImageButton) e.Row.Cells[lastCellIndex].Controls[0];
deleteButton.OnClientClick =
"if (!window.confirm('Are you sure you want to delete this item?')) return false;";

In this case the last cell is an asp:CommandField with ButtonType="Image". Be wary of the double submit issue if you use this approach. Also note that we only return false if the user cancels (i.e. window.confirm returns false). If we just return the result of window.confirm we might end up skipping the JavaScript-triggered postback even if the user wants to go ahead!