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 mouse click somewhere by accident. And what would be even nicer is if this confirmation takes place on the client (browser) instead of requiring yet another round trip to the server.
Fortunately, this task is very easy to do. As you might expect, the answer is to use 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.
<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('Delete this item?');">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Listing 1: Javascript to confirm deleting a GridView item.
This simple javascript calls confirm(), 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.
So, that’s 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.