Main FAQ Category: GridView (2)
Also in: Controls (14) 
How to add Client-Side confirmation when deleting items in GridView?
Posted: 23-Mar-2008
Updated: 23-Mar-2008
Views: 6274

When using ASP.NET GridView component, its really easy to display rows of data from database
or from some other source.
GridView also has built-in support for deleting and editing that data.
What GridView lacks is the out-of-the-box solution for confirmation dialogs for some critical
operations like Deleting of some important data.
Fortunately, there is an easy solution for this common requirement.
We only need to add one TemplateField to the Columns of the GridView, and to add standard 
ASP.NET LinkButton component to the ItemTemplate.
Next we must set CommandName="Delete" property on LinkButton and then we can use controls 
OnClientClick event handler to add simple JavaScript confirmation box that will pop-up on the
users screen when he clicks on this Delete link.
Here is the actual code snippet from the GridView declaration on page:
  <asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton CommandName="Delete" runat="server" Text="Delete" 
OnClientClick
="return confirm('Are you sure you want to delete this data Row?')" />
    </ItemTemplate>
</asp:TemplateField>

 
what happens here is that when user click on LinkButton, he is prompted with the confirmation dialog. This is done by using the built-in JavaScript command confirm.
If user clicks Yes then this command returns true and our data is deleted, but if user clicks
NO then the confirm returns false and no further operations are done, so our data will not
be deleted.