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=...

SonarQube Configuration For .NET Core Web API

When multiple developers are working on the same project, it's good to have a code review. SonarQube is a tool through which we can evaluate our code. Here, for demo purposes, we are going to evaluate the web API which is built on .NET Core. Let's see step by step implementation. In order to run SonarQube, we need to install JAVA in our local system.   Refer to the below link to download JAVA installer and install JAVA. https://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html Configure the 'PATH' system variable under environment variables Go to Control Panel > System > Advanced System Settings, it will open the System Properties window. Click on the "Environment Variables" button. Click on the "View" button under User Variables. Give the variable name as 'JAVA_HOME'. The variable value will be your JDK path where you installed JAVA. Select path variable under system variable and click o...

Automate Git Commands Across Repos Using Batch Scripts

  Writing Scripts to Apply Commands Across Repositories I store all of my local repositories in a particular directory. I wrote these scripts to automate one or more git commands to run on each repository within that directory. It could also be used to do a general clean-up before committing anything to your repository. Here are two ways to do it. Method 1: Use this when you want to store commands in a single file to be executed in sequence for every repo in your directory. 1 @echo off 2 ​ 3 for /d %%i in (%cd%\*) do ( 4 echo ************************************************************************* 5 ​ 6 echo "%%i" 7 cd "%%i" 8 ​ 9 echo ----------------------------------------- 10 echo status 11 git status 12 echo ----------------------------------------- 13 ​ 14 echo ************************************************************************* 15 ) 16 ​ 17 cd .. 18 ​ The script is simple: It’s composed of a single for loop. W...