Description
Hi, I have faced a problem while working with GridView and DataGrid in ASP.Net for confirmation box while deleting items. This is the scenario in each web application.
This is not too much harder. Its just a trick with Javascript. When we fire postback on button click initially it checks if any Javascript or any other Client-Side script is registered for the button and if it is present then it runs the Client-Side script. After returning with true value from the client script it do PostBacks to the web server.
Firstly you take a GridView (V 2.0) or DataGrid (V 1.1) on the web page. Add the template columns for the database fields as well take a additional template column for Delete Button. Add a Command Button with Label Delete and CommanName CMDDelete to identify between the RowCommand (V 2.0) or ItemCommand(1.1). Register RowCommand(V 2.0)Â ro ItemCommand(V 1.1).
There are two scenarios to solve this Problem-
- Design time
- Programmatically
SCENARIO I (Design Time)
By adding OnClientClick property to delete button and add simply Javascript Confirm Box eg. return confirm("Do you want to delete Item?"); if you click yes it returns true else false and according to your choice it fires Postback.
GridView ID="dgArticlesList" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="0px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" ShowHeader="False" AllowPaging="True" OnPageIndexChanging="dgArticlesList_PageIndexChanging" OnRowDataBound="dgArticlesList_RowDataBound" OnRowCommand="dgArticlesList_RowCommand" Width="700px">
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" runat="server" CommandName="CMDDelete" OnClientClick="return Confirm('Do you want to delete item?');">Deleteasp:LinkButton> ...
SCENARIO II (Programmatically)
While binding data to GridView find the delete button control in RowDataBound (V 2.0) or ItemDataBound( V 1.1) and add the javascript by using Attributes.Add() method. For eg.
btnConfirm.Attributes.Add("onclick","return confirm('Do you want to Delete');");
By this way you can Add the Confirm Delete for GridView as well DataGrid.