Click here to Skip to main content
Click here to Skip to main content

GridView Delete, with Confirmation

By , 10 Jan 2006
 

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:

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

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.

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.

<asp:GridView DataKeyNames="CategoryID" ID="GridView1" 
     runat="server" AutoGenerateColumns="False" 
     OnRowCommand="GridView1_RowCommand" 
     OnRowDataBound="GridView1_RowDataBound"
     OnRowDeleted="GridView1_RowDeleted" 
     OnRowDeleting="GridView1_RowDeleting">
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

About the Author

azamsharp
Web Developer
United States United States
Member
I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.
 
HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.
 
HighOnCoding.com www.HighOnCoding.com
 

My Blog:

Blog

 

Buy my iPhone app ABC Pop

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to highlight record to be deleted?memberRoger G. Calhoun3 Apr '13 - 5:17 
GeneralMy vote of 5memberHeyThereLameMan7 Mar '13 - 9:27 
Questioncode for DeleteRecordsByID()memberMember 96328852 Mar '13 - 18:27 
QuestionCancel Deletionmemberklaydze27 Jan '13 - 14:52 
GeneralMy vote of 5memberMember 798058316 Nov '12 - 5:30 
QuestionThank You so muchmemberGeorge D'souza9 May '12 - 2:27 
QuestionDeleteRecordByID codingmemberkimberly wind27 Mar '12 - 21:40 
GeneralMy vote of 5memberRashed_7 Feb '12 - 19:17 
GeneralMy vote of 4membermail02nilesh28 Dec '11 - 20:54 
JokeThanksmemberPouriya.GH10 Apr '11 - 22:00 
GeneralThanks!memberbgainey8 Apr '11 - 21:43 
Generalgriview row deletionmembermandarapuamala28 Feb '11 - 23:34 
Generalmsg from venkatmembervenkatasatyanarayna11 Nov '10 - 20:31 
GeneralOther way to attach JavaScriptmemberaul_aya23 Aug '10 - 19:19 
GeneralMy vote of 5memberita_info3 Aug '10 - 3:39 
Generali'm getting an error...membershantanu sinha22 Jul '10 - 9:09 
GeneralMy vote of 5membershantanu sinha22 Jul '10 - 9:02 
GeneralI am not getting a postbackmemberGeorge Viveiros8 Jan '10 - 7:42 
GeneralRe: I am not getting a postbackmemberAmos Cividalli14 Sep '10 - 22:28 
GeneralCHECK THIS OUT - Easiest solution so far...memberJose Mesona26 Aug '09 - 18:01 
Generalanother waymemberHenry Senior18 Jun '09 - 3:13 
GeneralProblem with comfirmmemberbinchentx3 Jun '09 - 6:31 
Generalstill have a questionmemberNatuliya21 Apr '09 - 8:27 
GeneralRe: still have a questionmemberazamsharp21 Apr '09 - 8:31 
GeneralRe: still have a questionmemberNatuliya21 Apr '09 - 8:54 
Generalfinememberexcelsoft200818 Feb '09 - 2:57 
GeneralIndex was out of range. Must be non-negative and less than the size of the collection (solution found)memberBusterCoder15 Dec '08 - 20:13 
GeneralIndex was out of range. Must be non-negative and less than the size of the collection.memberBusterCoder15 Dec '08 - 20:00 
Generalproblem with gridviewmembersrikanth.penmetsa24 Nov '08 - 19:04 
GeneralThanksmemberTabitutza30 Sep '08 - 3:18 
GeneralRefreshing (F5)memberfrancoisdotnet6 Aug '08 - 11:24 
Generalgrid view refreshmemberVnay Jagtap25 Jul '08 - 22:20 
GeneralGreat example of capturing the Primary Keymemberrichard.keslar6 Jun '08 - 4:59 
Generalworks for me thanksmemberjefferycxl17 Apr '08 - 16:49 
GeneralDelete confirmationmembernaresh13826 Dec '07 - 0:50 
QuestionGridview row deletion requires two clicksmemberstelban16 Oct '07 - 8:08 
Generalthanx azam sirmemberZubair Alam13 Sep '07 - 23:28 
GeneralRe: thanx azam sirmemberazamsharp14 Sep '07 - 7:06 
GeneralProblem with RowDataBound event in VBmemberjonefer31 Aug '07 - 12:03 
GeneralRe: Problem with RowDataBound event in VBmemberSpiff Dog9 Sep '08 - 4:17 
GeneralThank You Great JobmemberMahesh.J24 Aug '07 - 19:46 
GeneralThank youmemberzarchi26 Jun '07 - 1:29 
GeneralIt works perfectly & thanx alotmemberasankalk6 Jun '07 - 4:54 
GeneralGetting an errormemberSirving24 Apr '07 - 7:47 
GeneralRe: Getting an errormemberSirving25 Apr '07 - 5:21 
GeneralRe: Getting an errormemberrajdon1924 Jul '10 - 0:41 
GeneralJust use OnClientClickmemberHarelSeligmann21 Mar '07 - 6:17 
GeneralDataKeyNames and DataKeysmemberahmarshi17 Jan '07 - 3:04 
GeneralRe: DataKeyNames and DataKeysmemberHarelSeligmann21 Mar '07 - 6:12 
GeneralGrid View, deletemembernour12319 Nov '06 - 10:42 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 10 Jan 2006
Article Copyright 2006 by azamsharp
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid