Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Easily add a confirm message before a delete from a GridView

2.83/5 (11 votes)
23 May 2007CPOL 1  
Easily add confirmation code before deleting a row in a GridView, from code-behind.

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:

C#
//
protected void gvBooks_RowDataBound(object sender, GridViewRowEventArgs e)
{
  AddConfirmDelete((GridView)sender, e);
}

/// <summary>
/// If the gridview has a command field where showdeletebutton is true, then 
/// it add a confirm message. 
/// This function should be called in the RowDataBound event
/// </summary>

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?\")");
    }
   }
  }
 }
}//

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)