Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Article

GridView Delete, with Confirmation

Rate me:
Please Sign up or sign in to vote.
4.73/5 (69 votes)
10 Jan 20063 min read 937.6K   10.3K   160   80
How to implement row deletion in GridView, with confirmation.

Introduction

Everyone likes a confirmation that lets them know that a record is being deleted. In this article, I will show you how you can prompt confirmation boxes when you delete a record from the GridView control.

Implementing the Confirmation Feature

The first thing that you need to do is to attach the JavaScript confirmation code to the delete column of the GridView control. This can be done in the Row_DataBound event of the GridView control. The Row_DataBound event is fired whenever the row is attached to the GridView. Hence, this is fired when the GridView is building for the first time or even when the page is reloaded.

Let's see the HTML part of the GridView code:

HTML
<asp:GridView DataKeyNames="CategoryID" ID="GridView1" 
       runat="server" AutoGenerateColumns="False" 
       OnRowCommand="GridView1_RowCommand" 
       OnRowDataBound="GridView1_RowDataBound" 
       OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
  <Columns>
   <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
   <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
   <asp:TemplateField HeaderText="Select">
     <ItemTemplate>
       <asp:LinkButton ID="LinkButton1" 
         CommandArgument='<%# Eval("CategoryID") %>' 
         CommandName="Delete" runat="server">
         Delete</asp:LinkButton>
     </ItemTemplate>
   </asp:TemplateField>
  </Columns>
</asp:GridView>

As you can see from the above code, I have three columns in the GridView. Columns CategoryID and CategoryName are the bound columns, and the column Delete is a template column. The command argument is set as the CategoryID which means that whenever the LinkButton is clicked, it will pass CategoryID as an argument. The CommandName is set to "Delete".

The CommandName property is very important. If you have a LinkButton or a Button control inside the template column of the GridView control and the CommandName property is set to "Delete", then apart from GridView_RowCommand event, the GridView_Row_Deleting event is also fired.

Now, let's see the GridView_RowBound event where I attach the JavaScript code to every LinkButton.

C#
protected void GridView1_RowDataBound(object sender, 
                         GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1"); 
    l.Attributes.Add("onclick", "javascript:return " +
    "confirm('Are you sure you want to delete this record " +
    DataBinder.Eval(e.Row.DataItem, "CategoryID") + "')"); 
  }
}

In the above code, I checked whether the GridView row is a DataRow, and if it is, I simply attach some JavaScript code using the Attributes.Add method.

Catching the Primary Key of the Clicked Row

Now that you have successfully attached the JavaScript code to the GridView control, all that is left is to catch the primary key of the row which you have clicked so that you can perform further operations (like deleting the row). Remember what I said about a LinkButton or a Button control with the CommandName set to "Delete"? If you don't, read the text in the box again.

The CommandName property is very important. If you have a LinkButton or a Button control inside the template column of the GridView control and the CommandName property is set to "Delete", then apart from the GridView_RowCommand event, the GridView_Row_Deleting event is also fired.

Now, since our LinkButton's CommandName is set to "Delete", it means we have two choices of getting the primary key from the GridView. We can do this in the RowCommand event, or we can do this in the Row_Deleting event. I am going to show you both of them.

Catching the primary key in the RowCommand event

This is pretty simple. All you need to do is to get the value from the CommandArgument property which you have already set to the CategoryID.

C#
protected void GridView1_RowCommand(object sender, 
                         GridViewCommandEventArgs e)
{
  if (e.CommandName == "Delete")
  {
    // get the categoryID of the clicked row
    int categoryID = Convert.ToInt32(e.CommandArgument);
    // Delete the record 
    DeleteRecordByID(categoryID);
    // Implement this on your own :) 
  }
}

e.CommandArgument returns object so you need to convert it to int as I have done above.

Catching the primary key in the Row_Deleting event

Let's see how we can catch the primary key of the clicked row in the Row_Deleting event.

HTML
<asp:GridView DataKeyNames="CategoryID" ID="GridView1" 
     runat="server" AutoGenerateColumns="False" 
     OnRowCommand="GridView1_RowCommand" 
     OnRowDataBound="GridView1_RowDataBound"
     OnRowDeleted="GridView1_RowDeleted" 
     OnRowDeleting="GridView1_RowDeleting">
C#
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  int categoryID = (int) GridView1.DataKeys[e.RowIndex].Value;
  DeleteRecordByID(categoryID); 
}

In the above technique, you must set the DataKeyNames property of the GridView to "CategoryID". The GridView1.DataKeys[e.RowIndex].Value property gets the CategoryID out of the row which is clicked. I have attached the source code files with this project so please feel free to download them.

I hope you liked this article, happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
PraiseSample code delete gridview row Pin
Member 1337624919-Aug-21 5:04
Member 1337624919-Aug-21 5:04 
Questionerror in index Pin
Member 125045015-May-16 2:09
Member 125045015-May-16 2:09 
QuestionIt worked perfectly well Pin
matmape7-Oct-14 23:43
matmape7-Oct-14 23:43 
Questionerror occured: if (e.CommandName == "Delete") Line 42: { Line 43: int CategoryID = Convert.ToInt32(e.CommandArgument); Line 44: // Delete the record Line 45: DeleteRecordByID(CategoryID); Pin
member143129-Jan-14 23:23
member143129-Jan-14 23:23 
AnswerRe: error occured: if (e.CommandName == "Delete") Line 42: { Line 43: int CategoryID = Convert.ToInt32(e.CommandArgument); Line 44: // Delete the record Line 45: DeleteRecordByID(CategoryID); Pin
Elias Mauro Antioco Murgia14-Mar-16 7:04
Elias Mauro Antioco Murgia14-Mar-16 7:04 
QuestionHow to highlight record to be deleted? Pin
Roger G. Calhoun3-Apr-13 5:17
Roger G. Calhoun3-Apr-13 5:17 
GeneralMy vote of 5 Pin
HeyThereLameMan7-Mar-13 9:27
HeyThereLameMan7-Mar-13 9:27 
Questioncode for DeleteRecordsByID() Pin
Ravi Kant Srivastava2-Mar-13 18:27
professionalRavi Kant Srivastava2-Mar-13 18:27 
AnswerRe: code for DeleteRecordsByID() Pin
Member 1278724620-Oct-16 1:16
Member 1278724620-Oct-16 1:16 
QuestionCancel Deletion Pin
klaydze27-Jan-13 14:52
klaydze27-Jan-13 14:52 
GeneralMy vote of 5 Pin
Michael Breeden16-Nov-12 5:30
Michael Breeden16-Nov-12 5:30 
QuestionThank You so much Pin
George D'souza9-May-12 2:27
George D'souza9-May-12 2:27 
QuestionDeleteRecordByID coding Pin
kimberly wind27-Mar-12 21:40
kimberly wind27-Mar-12 21:40 
GeneralMy vote of 5 Pin
Member 105108227-Feb-12 19:17
professionalMember 105108227-Feb-12 19:17 
GeneralMy vote of 4 Pin
Nilesh Patil Kolhapur28-Dec-11 20:54
Nilesh Patil Kolhapur28-Dec-11 20:54 
JokeThanks Pin
Pouriya Ghamary10-Apr-11 22:00
Pouriya Ghamary10-Apr-11 22:00 
GeneralThanks! Pin
bgainey8-Apr-11 21:43
bgainey8-Apr-11 21:43 
Generalgriview row deletion Pin
mandarapu28-Feb-11 23:34
mandarapu28-Feb-11 23:34 
Generalmsg from venkat Pin
venkatasatyanarayna11-Nov-10 20:31
venkatasatyanarayna11-Nov-10 20:31 
GeneralOther way to attach JavaScript Pin
aul_aya23-Aug-10 19:19
aul_aya23-Aug-10 19:19 
GeneralMy vote of 5 Pin
ita_info3-Aug-10 3:39
ita_info3-Aug-10 3:39 
Generali'm getting an error... Pin
shantanu sinha22-Jul-10 9:09
shantanu sinha22-Jul-10 9:09 
GeneralMy vote of 5 Pin
shantanu sinha22-Jul-10 9:02
shantanu sinha22-Jul-10 9:02 
GeneralI am not getting a postback Pin
George Viveiros8-Jan-10 7:42
George Viveiros8-Jan-10 7:42 
GeneralRe: I am not getting a postback Pin
Amos Cividalli14-Sep-10 22:28
Amos Cividalli14-Sep-10 22:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.