Display Confirmation Message on Gridview Deleting

Write Javascript into head tag………

<head runat=”server”>
    <title>GridView Data Manipulation</title>
    <script type=”text/javascript” language=”javascript”>
        function ConfirmOnDelete(item)
        {
          if (confirm(“Are you sure to delete: ” + item + “?”)==true)
            return true;
          else
            return false;
        }
    </script>
</head>

Aspx page: Gridview

<Columns>
    <asp:BoundField DataField=”CustomerID” HeaderText=”ID” ReadOnly=”true” />
    <asp:BoundField DataField=”CompanyName” HeaderText=”Company”/>
    <asp:BoundField DataField=”ContactName” HeaderText=”Name”/>
    <asp:BoundField DataField=”ContactTitle” HeaderText=”Title” />
    <asp:BoundField DataField=”Address” HeaderText=”Address”/>
    <asp:BoundField DataField=”Country” HeaderText=”Country”/>
    <asp:CommandField ShowDeleteButton=”True” ShowEditButton=”True” />
</Columns>

.CS Page

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
   {
     if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
     {
       string id = e.Row.Cells[0].Text; // Get the id to be deleted
       LinkButton lb = (LinkButton)e.Row.Cells[6].Controls[2]; //cast the ShowDeleteButton link to linkbutton
       if (lb != null)
       {
          lb.Attributes.Add(“onclick”, “return ConfirmOnDelete(‘” + id + “‘);”); //attach the JavaScript function with the ID as the paramter
       }      
      }
  }
}
Share