Friday, June 3, 2011

How to add Client-Side confirmation when deleting items in GridView?

Dear Googler,
When using ASP.NET GridView component, its really easy to display rows of data from 
database or from some other source.

In GridView there is no confirmation dialogs for 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 
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/she 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>


Here Confirm is the built-in javascript command. 
If user click the link button, the confirmation dialog will appear using the 
"Confirm" JavaScript function. If user click the yes button it will return true 
and our data is deleted, but user clicks No button it will return no and our data 
are not deleted.

No comments:

Post a Comment