Login


Confirm Before Deleting GridView Item

By Jonathan Wood on 12/2/2010 (Updated on 12/7/2010)
Language: JavaScript
Technology: ASP.NET
Platform: Windows
License: CPOL
Views: 9,170
Web Development » ASP.NET Controls » Grid Controls » Confirm Before Deleting GridView Item

Introduction

When deleting an item in one of the ASP.NET grids, it would be nice to ask the user to confirm this is what they really meant to do. After all, it is very easy to click the mouse somewhere by accident. And what would be even nicer is if this confirmation took place on the client side (browser) instead of requiring yet another round trip to the server.

JavaScript Solution

Fortunately, this task is very easy to do using a bit of JavaScript. In some cases, setting up JavaScript on an ASP.NET page can get a little involved. However, a simple script can be added using the OnClientClick property, which is available with many ASP.NET controls.

Listing 1 shows part of the ASP.NET code for a GridView control. This code includes an ItemTemplate that defines a delete button and includes some confirmation JavaScript in the OnClientClick property.

Listing 1: JavaScript to confirm deleting a GridView item

<asp:GridView ID="GridView1" runat="server" />
  <Columns>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:LinkButton ID="lnkDelete" runat="server"
          CausesValidation="false" 
          CommandName="DeleteItem"
          Text="Delete" CommandArgument='<%# Bind("ItemID") %>'
          OnClientClick="return confirm('Really delete this item?');">
        </asp:LinkButton>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

This simple JavaScript calls the confirm() method, which returns true if the user selects Yes. The code associated with posting back the form and deleting the item only executes if this script returns true.

Conclusion

This is a very simple technique that is easy to implement and works very well. And because it uses JavaScript, it doesn't perform the postback to the server unless the user confirms they really do want to delete the grid item.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.