[asp.net] How to add a "confirm delete" option in ASP.Net Gridview?

How to add a "confirm delete" option in ASP.Net Gridview ?

This question is related to asp.net gridview

The answer is


I was having problems getting a commandField Delete button to honor the 'return false' response to when a user clicked cancel on the 'Are you sure' pop-up that one gets with using the javascript confirm() function. I didn't want to change it to a template field.

The problem, as I see it, was that these commandField Buttons already have some Javascript associated with them to perform the postback. No amount of simply appending the confirm() function was effective.

Here's how I solved it:

Using JQuery, I first found each delete button on the page (there are several), then manipulated the button's associated Javascript based on whether the visitor agreed or canceled the confirming pop-up.

<script language="javascript" type="text/javascript">
$(document).ready(function() {

               $('input[type="button"]').each(function() {

                   if ($(this).val() == "Delete") {
                       var curEvent = $(this).attr('onclick');
                       var newContent = "if(affirmDelete() == true){" + curEvent + "};" 
                       $(this).attr('onclick',newContent);                       
                   }
               });
}

function affirmDelete() {    
               return confirm('Are you sure?');
}
</script>

I quite like adding the code in the GridView RowDataBound event to inform the user exactly which item they are trying to delete. Slightly better user experience?

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        LinkButton lnkBtnDelete = e.Row.FindControl("lnkBtnDelete") as LinkButton;

        // Use whatever control you want to show in the confirmation message
        Label lblContactName = e.Row.FindControl("lblContactName") as Label;

        lnkBtnDelete.Attributes.Add("onclick", string.Format("return confirm('Are you sure you want to delete the contact {0}?');", lblContactName.Text));

    }

}

If your Gridview used with AutoGenerateDeleteButton="true" , you may convert it to LinkButton:

  1. Click GridView Tasks and then Edit Columns. https://www.flickr.com/photos/32784002@N02/15395933069/

  2. Select Delete in Selected fields, and click on Convert this field into a TemplateField. Then click OK: https://www.flickr.com/photos/32784002@N02/15579904611/

  3. Now your LinkButton will be generated. You can add OnClientClick event to the LinkButton like this:
    OnClientClick="return confirm('Are you sure you want to delete?'); "


You can do using OnClientClick of button.

OnClientClick="return confirm('confirm delete')"

I like this way of adding a confirmation prompt before deleting a record from a gridview. This is the CommandField definition nested within a GridView web control in the aspx page. There's nothing fancy here--just a straightforward Commandfield.

_x000D_
_x000D_
<asp:CommandField ShowEditButton="true" UpdateText="Save" ShowDeleteButton="True">_x000D_
  <ControlStyle CssClass="modMarketAdjust" />_x000D_
</asp:CommandField>
_x000D_
_x000D_
_x000D_

Then, all I had to do was add some code to the RowDeleting event of the GridView control. This event fires before the row is actually deleted, which allows you to get the user's confirmation, and to cancel the event if he doesn't want to cancel after all. Here is the code that I put in the RowDeleting event handler:

Private Sub grdMarketAdjustment_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles grdMarketAdjustment.RowDeleting
  Dim confirmed As Integer = MsgBox("Are you sure that you want to delete this market adjustment?", MsgBoxStyle.YesNo + MsgBoxStyle.MsgBoxSetForeground, "Confirm Delete")
  If Not confirmed = MsgBoxResult.Yes Then
    e.Cancel = True 'Cancel the delete.
  End If
End Sub

And that seems to work fine.


This is my preferred method. Pretty straight forward:

http://www.codeproject.com/KB/webforms/GridViewConfirmDelete.aspx


Although many of these answers will work, this shows a straightforward example when using CommandField in GridView using the OnClientClick property.

ASPX:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"... >
<Columns>
<!-- Data columns here -->
        <asp:CommandField ButtonType="Button" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
</Columns>
</asp:GridView>

ASPX.CS:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
    {
        (e.Row.Cells[2].Controls[2] as Button).OnClientClick = "return confirm('Do you want to delete this row?');";
    }
}

I love the JavaScript solution and have some updates to work with dynamic ajax loading:

     $(document).on("click", "a", function () {
        if (this.innerHTML.indexOf("Delete") == 0) {
            return confirm("Are you sure you want to delete this record?");
        }
    });

Hope it help ;)


This is my method and it works perfectly.

asp

 <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="5%" HeaderStyle-Width="5%" HeaderStyle-CssClass="color" HeaderText="Edit"
                                EditText="<span style='font-size: 20px; color: #27ae60;'><span class='glyphicons glyph-edit'></span></span>"
                                DeleteText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-bin'></span></span>"
                                CancelText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-remove-2'></span></span>" 
                                UpdateText="<span style='font-size: 20px; color: #2980b9;'><span class='glyphicons glyph-floppy-saved'></span></span>" />

C# (replace 5 with the column number of the button)

        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {

        }
        else {
            ((LinkButton)e.Row.Cells[5].Controls[2]).OnClientClick = "return confirm('Do you really want to delete?');";

        }

This code is working fine for me.

jQuery("a").filter(function () {
        return this.innerHTML.indexOf("Delete") == 0;
        }).click(function () { return confirm("Are you sure you want to delete this record?"); 
});

I didn't want any image so i modified the answer given by @statmaster to make it simple entry along with the other columns.

<asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this entry?');">Delete </asp:LinkButton>             
        </ItemTemplate>
</asp:TemplateField>

The colour of the text can be changed using the Forecolor Property.


I did this a bit different. In my gridview I set the AutoGenerateDeleteButton="true". To find the delete button I use jQuery and add a click event to the found Anchors.

jQuery("a").filter(function () {
        return this.innerHTML.indexOf("Delete") == 0;
        }).click(function () { return confirm("Are you sure you want to delete this record?"); 
});

This is quick and simple for what I need to do. Just be mindful that Every Anchor in the page that displays Delete will be selected by jQuery and will have the event added to it.


Try this:

I used for Update and Delete buttons. It doesn't touch Edit button. You can use auto generated buttons.

  protected void gvOperators_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType != DataControlRowType.DataRow) return;
        var updateButton = (LinkButton)e.Row.Cells[0].Controls[0];
        if (updateButton.Text == "Update")
        {
            updateButton.OnClientClick = "return confirm('Do you really want to update?');";
        }
        var deleteButton = (LinkButton)e.Row.Cells[0].Controls[2];
        if (deleteButton.Text == "Delete")
        {
            deleteButton.OnClientClick = "return confirm('Do you really want to delete?');";
        }

    }