Thursday, April 8, 2010

Confirming Delete in a GridView

I tried a bunch of ways but this was the only way to get this to work reliably. The problem is that the ButtonFields in the GridView don’t have an OnClientClick event the way that every other button does. To remedy this, you have to attach the ClientClick handler when the grid is being generated.

So in your Columns collection of the GridView, you will have a button field like this:

<asp:ButtonField ButtonType="Link" CommandName="Clear" Text="Clear" />

Then in the code behind you need to do this:

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

int lastCellIndex = e.Row.Cells.Count - 1;
LinkButton clearButton = (LinkButton)e.Row.Cells[lastCellIndex].Controls[0];
clearButton.OnClientClick =
"if (!window.confirm('Are you sure you want to clear this score?')) return false;";
}

No comments:

Post a Comment