JavaScript

Show JavaScript Confirmation message while deleting ASP.Net Grid Row

Many a time , we need a confirmation Message on deleting ASP.Net Gird Row . Coz if any User mistakenly clicks the delete button , the data will be gone . So its always the Best to use Confirmation on Deleting .

We will see a demo now how to Show JavaScript/Client Side Confirmation Msg while deleting an ASP.Net Grid Row .

A long time ago ,I had to use more brain processing power to do this requirement ūüôā So I thought to share with all .

Lets see the below image for what I am gonna do :

Show JavaScript Confirmation message while deleting  ASP.Net Grid Row

Show JavaScript Confirmation message while deleting ASP.Net Grid Row

Add this markup inside your ASP.Net Grid .

<asp:TemplateField HeaderText="" ShowHeader="False" HeaderStyle-HorizontalAlign="Left">
                            <ItemTemplate>      
                                      <asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False" CommandName="Delete"
                                    Text="Delete" OnClientClick="ConfirmDelete(this.id)" ></asp:LinkButton>
                            </ItemTemplate>
                            <HeaderStyle HorizontalAlign="Left" />
                      </asp:TemplateField>

And the JavaScript method implementation of the ConfirmDelete(this.id) is like below –

function ConfirmDelete(RowId)
     {
         var rowNoStr = RowId.split('_');
         rowNo = parseInt(rowNoStr[3]) + 1;              
    
         var confirm_value = document.createElement("INPUT");
         confirm_value.type = "hidden";
         confirm_value.name = "confirm_value";

         var grid = document.getElementById('<%=gvTicketDetails.ClientID%>');

         var delText = "Are you sure to delete - ";
         var ticketNo ="Tk " + grid.rows[rowNo].cells[0].innerText + " : ";
         var ticketTitle = grid.rows[rowNo].cells[1].innerText + " ?";
         var delMsg = delText.concat(ticketNo, ticketTitle);

         var answer = confirm(delMsg);
         if (answer)
         {
             confirm_value.value = "Yes";
         }
         else
         {
             confirm_value.value = "No";
         }
         document.forms[0].appendChild(confirm_value);       
     }

And now using the below code , you can easily get the confirmation value at server side .

protected void gvTicketDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string confirmValue = Request.Form["confirm_value"];
            if (confirmValue.ToUpper() == "YES")
            {
                
            }
        }

You are done ūüôā Cheers

Standard