5,668,748 members and growing! (11,676 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate

GridView Delete, with Confirmation

By azamsharp

How to implement row deletion in GridView, with confirmation.
C#, Windows, .NET, Visual Studio, ASP.NET, ADO.NET, Dev

Posted: 10 Jan 2006
Updated: 10 Jan 2006
Views: 243,655
Bookmarked: 87 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
30 votes for this Article.
Popularity: 6.34 Rating: 4.29 out of 5
1 vote, 3.3%
1
1 vote, 3.3%
2
2 votes, 6.7%
3
5 votes, 16.7%
4
21 votes, 70.0%
5

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


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.

ScreencastADay is a website committed to educate you everyday. The idea of the website is really simple. We believe that in order to be successful you need to learn something new everyday. ScreencastADay puts this thought into action by providing new screencast every day. This means you will get 7 screencasts a week and 365 screencasts a year unless of course it is a leap year in that case you get one more bonus screencast.

HighOnCoding.com www.HighOnCoding.com

ScreencastADay.com: www.ScreencastADay.com

RefactorCode: www.RefactorCode.com

GridViewGuy: GridViewGuy

My Blog:

Blog

Occupation: Web Developer
Location: United States United States

Other popular ASP.NET Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 44 (Total in Forum: 44) (Refresh)FirstPrevNext
GeneralThanksmemberTabitutza4:18 30 Sep '08  
GeneralRefreshing (F5)memberfrancoisdotnet12:24 6 Aug '08  
Generalgrid view refreshmemberVnay Jagtap23:20 25 Jul '08  
GeneralGreat example of capturing the Primary Keymemberrichard.keslar5:59 6 Jun '08  
Generalworks for me thanksmemberjefferycxl17:49 17 Apr '08  
GeneralDelete confirmationmembernaresh13821:50 6 Dec '07  
QuestionGridview row deletion requires two clicksmemberstelban9:08 16 Oct '07  
Generalthanx azam sirmemberZubair Alam0:28 14 Sep '07  
GeneralRe: thanx azam sirmemberazamsharp8:06 14 Sep '07  
GeneralProblem with RowDataBound event in VBmemberjonefer13:03 31 Aug '07  
GeneralRe: Problem with RowDataBound event in VBmemberSpiff Dog5:17 9 Sep '08  
GeneralThank You Great JobmemberMahesh.J20:46 24 Aug '07  
GeneralThank youmemberzarchi2:29 26 Jun '07  
GeneralIt works perfectly & thanx alotmemberasankalk5:54 6 Jun '07  
GeneralGetting an errormemberSirving8:47 24 Apr '07  
GeneralRe: Getting an errormemberSirving6:21 25 Apr '07  
GeneralJust use OnClientClickmemberHarelSeligmann7:17 21 Mar '07  
GeneralDataKeyNames and DataKeysmemberahmarshi4:04 17 Jan '07  
GeneralRe: DataKeyNames and DataKeysmemberHarelSeligmann7:12 21 Mar '07  
GeneralGrid View, deletemembernour12311:42 19 Nov '06  
GeneralWorked for Atlas troubles, toomemberMarley's Ghost11:18 10 Oct '06  
GeneralGood tutorial!memberkaka13521:54 8 Aug '06  
GeneralImage Button Doesn't Workmembercavedog66:16 14 Jul '06  
GeneralRe: Image Button Doesn't Workmemberkaka13521:49 8 Aug '06  
GeneralRe: Image Button Doesn't Workmemberwarderblu7:55 11 Oct '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 10 Jan 2006
Editor: Smitha Vijayan
Copyright 2006 by azamsharp
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project