Skip to main content

Display Confirmation Message on GridView Deleting

Display Confirmation Message on GridView Deleting

This demo describes the different approach to display a confirmation message when deleting a row in GridView and pass the id of the item to the confirmation message. Confirmation means a user is asked first if he/she wanted to delete a record by choosing an option (OK and CANCEL).
In this demo, we use the JavaScript confirm function for displaying the confirmation message. Now let’s create our JavaScript confirm function. To do this switch to ASPX source and add the following code block within the <head> tag like:
<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>
Since we are done setting up our JavaScript function, we can simply call that function in our codes when deleting a row in GridView. Here are the following approaches below:
Option A: Using the ShowDeleteButton CommandField
The ShowDeleteButton CommandField is a built-in command in GridView to preform delete. I used this option in my previous example about “GridView Edit, Insert,Update and Delete” for deleting the data . Here’s a way to attach our JavaScript confirm in our codes when using ShowDeleteButton.
Assuming that we have this GridView Column mark up:
<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>
At RowDataBound event, we can add an attribute to the control for calling the JavaScript confirm function when deleting. See below
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
       }      
      }
  }
}
As you can see from the above code blocks, we attached the JavaScript function in the LinkButton by adding an attributes to the control. But before that we need to check the RowState of the GridView first to ensure that the GridView is not on Edit Mode. If you failed to check for its RowState then you will get unexpected outcome. Second we checked for the RowType to ensure that we are on the right track for finding the control in the GridView. Please note that GridView is composed of six RowTypes namely (DataRow, EmptyDataRow, Header, Footer, Separator and Pager), so when accessing a control at RowDataBound event of GridView you must always check for its RowType.
We used the method Controls [index] because the CommandField columns doesn’t have an ID for us to use FindControl method. In addition we cannot even set an ID to a CommandField column.
As you can see, we passed the value of 6 in the cells index. This means that the ShowDeleteButton link is located at the 7th column of the GridView (see GridView mark up above), by default cells index starts at 0.
We passed the value of 2 in the Controls index in order to get reference to the ShowDeleteButton link. Based from the GridView mark up above we can see the controls sequence at the 7th columns below.
e.Row.Cells[6].Controls[0] – index 0 reference to ShowEditButton link
e.Row.Cells[6].Controls[1] – index 1 reference to a Literal control that separates between the ShowEditButton and ShowDeleteButton.
e.Row.Cells[6].Controls[2] – index 2 reference to ShowDeleteButton link
e.Row.Cells[6].Controls[3] – you will get null reference expection when passing index 3 and up J
Option B: Using TemplateField with LinkButton
Assuming that we have this GridView Column mark up below
<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:TemplateField>
      <ItemTemplate>
      <asp:LinkButton ID="LinkDelete" runat="server">Delete</asp:LinkButton>
      </ItemTemplate>
 </asp:TemplateField>
</Columns>
The Declarative Approach:
When using TemplateField, we can directly use the OnClientClick event the ASPNET LinkButton server control and call the JavaScript confirm function at the mark up like below:
<ItemTemplate>
 <asp:LinkButton ID=" LinkDelete " runat="server" OnClick="LinkDelete _Click" OnClientClick="return ConfirmOnDelete('');">Delete</asp:LinkButton>
</ItemTemplate>
Note that using the above approach we cannot directly pass the value of the id to be deleted as a paramter in the confirm function that’s why we passed an empty value.
The Code Behind Approach:
The code behind approach is almost the same as what we did using the RowDataBound event for accessing the ShowDeleteButton. See below
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].FindControl("LinkDelete"); //access the LinkButton from the TemplateField using FindControl method
      if (lb != null)
      {
        lb.Attributes.Add("onclick", "return ConfirmOnDelete('" + id + "');"); //attach the JavaScript function
      }
     }
}
}

Comments

Popular posts from this blog

PNR Status by web Scraping Method (ASP.NET) C#

To Get the PNR Status by web Scraping Method Steps to Execute the Function Step 1 : Add the below method in your Form and Pass the PNR Number arguement public string GetPNRStatus( string sPNR) { string URI = "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi" ; string Parameters = Uri .EscapeUriString( "lccp_pnrno1=" +sPNR+ "&amp;submitpnr=Get Status" ); System.Net. HttpWebRequest req = ( HttpWebRequest )System.Net. WebRequest .Create(URI); //HTTP POST Headers req.ContentType = "application/x-www-form-urlencoded" ; req.Host = "www.indianrail.gov.in" ; //You can use your own user-agent. req.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0) DELL;Venue Pro" ; req.Headers.Add( HttpRequestHeader .AcceptLanguage, "en-us,en;q=0.5" ); req.Headers.Add( HttpRequestHeader .AcceptCharset, "ISO-8859-1,utf-8;q=
C# HttpClient tutorial C# HttpClient tutorial shows how to create HTTP requests with HttpClient in C#. In the examples, we create simple GET and POST requests. The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. HttpClient  is a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. C# HttpClient status code HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses (100–199) Successful responses (200–299) Redirects (300–399) Client errors (400–499) Server errors (500–599) Program.cs using System; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientStatus { class Program { static async Task Main(string[] args) { using var client = new

Popup form on Screen Center Javascript

Popup Form on Center  to popup the form on Screen Center use the below Script Example : <script language="javascript"> var popupWindow = null; function centeredPopup(url,winName,w,h,scroll){ LeftPosition = (screen.width) ? (screen.width-w)/2 : 0; TopPosition = (screen.height) ? (screen.height-h)/2 : 0; settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable' popupWindow = window.open(url,winName,settings) } </script> <p><a href="http://www.quackit.com/common/link_builder.cfm" onclick="centeredPopup(this.href,'myWindow','500','300','yes');return false">Centered Popup</a></p>