Introduction
Often you want to add a confirmation message for the user before deleting a row, say, from a GridView
control. This can, of course, easily be done by placing a link in an ItemTemplate
and adding the correct value in the OnClientClick
property. But if you want / have to do this from the code-behind, a dependency on your cell index will eventually be overseen, with possible disastrous results.
Background
Even though this can easily be done through the Cells
collection, one day, someone is going to add / move / remove a column without looking at the code behind.
Using the code
The code below will demonstrate how this can be done with a method that will find the delete buttons automatically and add the necessary code:
protected void gvBooks_RowDataBound(object sender, GridViewRowEventArgs e)
{
AddConfirmDelete((GridView)sender, e);
}
public static void AddConfirmDelete(GridView gv, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlField dcf in gv.Columns)
{
if (dcf.ToString() == "CommandField")
{
if (((CommandField)dcf).ShowDeleteButton == true)
{
e.Row.Cells[gv.Columns.IndexOf(dcf)].Attributes
.Add("onclick", "return confirm(\"Are you sure?\")");
}
}
}
}
}