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")
{
int categoryID = Convert.ToInt32(e.CommandArgument);
DeleteRecordByID(categoryID);
}
}
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!
|
|
 |
 | I am not getting a postback George Viveiros | 8:42 8 Jan '10 |
|
 |
I have tried this code in both the RoCommand and RowDeleting events. I get the popup but I do not get a post back.
|
|
|
|
 |
 | CHECK THIS OUT - Easiest solution so far... Jose Mesona | 19:01 26 Aug '09 |
|
|
 |
 | another way Henry Senior | 4:13 18 Jun '09 |
|
|
 |
 | Problem with comfirm binchentx | 7:31 3 Jun '09 |
|
 |
I have a GridView, that works fine with event GridView2_RowDeleting and GridView2_RowDeleted. But after I added GridView2_RowDataBound for comfirmation. The comfirm works fine, but it didn't fire RowDeleting and RowDeleted events any more. What I am missing?
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Delete") { // get the categoryID of the clicked row int reviewID = Convert.ToInt32(e.CommandArgument); // Delete the record } } protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e) { string KeyValue = GridView2.DataKeys[e.RowIndex].Value.ToString(); //GridView2.Rows[e.RowIndex].Visible = false; //PeerReviewControl.DeleteReview(int.Parse(KeyValue));
return; } protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ImageButton ib = (ImageButton)e.Row.Cells[0].Controls[0]; ib.Attributes.Add("onclick", "return " + "confirm('Are you sure you want to delete this review')"); } }
aspx---------------------- <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="Review_Id" OnRowCreated="GridView2_RowCreated" OnRowCommand="GridView2_RowCommand" OnRowDeleting="GridView2_RowDeleting" OnRowDataBound="GridView2_RowDataBound" AllowSorting="True" Width="100%"> <Columns> <asp:CommandField ButtonType="Image" DeleteImageUrl="Images/Delete.gif" ShowDeleteButton="True" > <HeaderStyle BackColor="#E0E0E0" HorizontalAlign="Left" VerticalAlign="Top" /> <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" /> </asp:CommandField> <asp:TemplateField HeaderText="Patient" SortExpression="PATIENT_NAME" >
|
|
|
|
 |
 | still have a question Natuliya | 9:27 21 Apr '09 |
|
 |
Sorry, I did not understand how do we know if user answers 'yes' or 'no' on the confirmation message. How do we send this 'true' or 'false' from the client side to the server side?
|
|
|
|
 |
|
 |
When the user selected "OK" then the postback proceeds and the item is deleted. When the user selects "Cancel" nothing happens. This is the default behavior of the confirmation box.
Mohammad Azam azamsharp@gmail.com www.highoncoding.com Houston, TEXAS
|
|
|
|
 |
|
 |
Thank you very much. I tried and it works for me.
|
|
|
|
 |
 | fine excelsoft2008 | 3:57 18 Feb '09 |
|
|
 |
 | Index was out of range. Must be non-negative and less than the size of the collection (solution found) BusterCoder | 21:13 15 Dec '08 |
|
 |
Hello,
I found the solution. To make the page refresh I had a bindgrid() on the RowComand event. Instead, I should have put the bindgrid() on the RowDeleting event. Works fine now. I have to admit, I'm not sure why it didn't work on the RowCommand event.
Thanks for the great tutorial and code. Bruce
|
|
|
|
 |
 | Index was out of range. Must be non-negative and less than the size of the collection. BusterCoder | 21:00 15 Dec '08 |
|
 |
Hello,
I have your code for the delete working fine except when trying to delete the last row (I have it sorted desc so actually the last row is id #1). I get "Index was out of range. Must be non-negative and less than the size of the collection." on this line in the RowDeleting event:
int ReferralId = Convert.ToInt32(gvList.DataKeys[e.RowIndex].Value.ToString());
I have tried some different syntax:
int ReferralId = (int)gvList.DataKeys[e.RowIndex].Value;
And tried to circumvent the error: if (e.RowIndex) > 0 { ...delete code }
I have been posting, cannot find the solution to this error. So I thought I would ask you because I am using your code. Any help to solve this would be greatly appreciated.
Thanks, Bruce
|
|
|
|
 |
 | problem with gridview srikanth.penmetsa | 20:04 24 Nov '08 |
|
 |
hi i am facing some difficulties in gridview.how to update,delete data in gridview by writing the code in c#.please let me know.please send the answer here or to my mailid.my mail id is srikanth.penmetsa@gmail.com
|
|
|
|
 |
 | Thanks Tabitutza | 4:18 30 Sep '08 |
|
 |
Thanks a lot! It was very useful to me!
Tabitha
|
|
|
|
 |
 | Refreshing (F5) francoisdotnet | 12:24 6 Aug '08 |
|
 |
Hi
I was doing a row delete in a similar way but I had the problem that if the client hit F5 to refresh the page it would attempt to delete the file again.
I tried your method but it seems to have the same problem? And it doesn't seem to update the gridview, i.e. the deleted row is still present. (I may be incorrect)
Is there a way to cause the page not to redelete when refreshed??
F
|
|
|
|
 |
 | grid view refresh Vnay Jagtap | 23:20 25 Jul '08 |
|
 |
on asp.net page i am calling one progress message while search operation running on page.After search complete i am seeting visibality hidden to div in which having progress image.Gridview is out side that dev but its not showing latest search result.Data binding is proper its working fine without this javascript function.Anybody guide me on same
|
|
|
|
 |
 | Great example of capturing the Primary Key richard.keslar | 5:59 6 Jun '08 |
|
 |
I wasn't sure how to get the Primary Key before looking at this example because my primary key is an identity field that I don't show anywhere in the aspx page except in the DataKeyNames attribute. Thanks for the tip. It was really helpful.
|
|
|
|
 |
 | works for me thanks jefferycxl | 17:49 17 Apr '08 |
|
 |
works for me thanks
Jefferycxl
|
|
|
|
 |
 | Delete confirmation naresh1382 | 1:50 6 Dec '07 |
|
 |
This is good but i need this in other way. The grid will have checkboxes on lefthand side in first column and there will be a asp button at bottom of the grid with caption Delete. upon clicking delete it should check whether atlease one check box is checked if not it should display a msg box stating that please check atleast one check box. Do you have any idea abt that. If yes can u explaing me how to do.
I wll be thankful to you if you solve this pblm hence i tried a lot but didnt get any solution. Help me
Thanks, naresh krishna chnareshkrishna@yahoo.co.in
|
|
|
|
 |
 | Gridview row deletion requires two clicks stelban | 9:08 16 Oct '07 |
|
 |
Great article! I am having the following problem. Hope you can help:
Objective is to click on the image in the gridview to delete the record from the database, rebind, and display the gridview showing that the record is gone. Problem is that it requires 2 clicks. The first click makes the page move slightly but it does not delete the record from the database. The second click displays the grid without the record and it displays the response.write text. If I remove the call to the deleteje sub, the response.write does display the jeid so the onrowcommand appears to be firing.
<asp:GridView ID="gv3" runat="server" BackColor="SkyBlue" HeaderStyle-BackColor="lightGray" DataKeyNames="ID" onrowcommand="modifyje" AlternatingRowStyle-BackColor="LightSteelBlue" AutoGenerateColumns="false" > <columns> <asp:TemplateField > <ItemTemplate > <asp:ImageButton runat="server" ImageUrl="/images/delete.gif" enabled="true" ToolTip="Delete" commandname="DeleteJE2" CausesValidation="false" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"id") %>' ID="deleteimage" /> </ItemTemplate> </asp:TemplateField> <asp:boundfield datafield="id" headertext="ID" /> <asp:boundfield datafield="name" headertext="Name" /> <asp:boundfield datafield="descr" headertext="Description" /> <asp:boundfield datafield="cr_div" headertext="Cr_Div" /> <asp:boundfield datafield="Cr_CC" headertext="Cr_CC" /> <asp:boundfield datafield="Cr_Acct" headertext="Cr_Acct" /> <asp:boundfield datafield="Bill_Div" headertext="Bill_Div" /> <asp:boundfield datafield="Bill_CC" headertext="Bill_CC" /> <asp:boundfield datafield="Db_Acct" headertext="Db_Acct" />
</columns> </asp:GridView>
Sub modifyje(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles gv3.RowCommand
'-------------------------------------------------------------------------- If (e.CommandName = "DeleteJE2") Then jeid = Convert.ToInt32(e.CommandArgument) Response.Write("jeid=" & jeid) Call deleteje(jeid) End If '-------------------------------------------------------------------------- End Sub
Sub deleteje(ByVal jeid As Integer)
Dim objctl As New JEController Dim objinfo As New JEInfo
objctl.JE_DeleteJE(jeid)
Dim ds2 As DataSet ds2 = objctl.JE_getJEList(lname,keywd,crdv,crcc) gv3.DataSource = ds2 gv3.DataBind()
End Sub
|
|
|
|
 |
 | thanx azam sir Zubair Alam | 0:28 14 Sep '07 |
|
 |
i read your number of article and everyone is too good
this article help me a lot.
thanx again azam sir.
|
|
|
|
 |
|
 |
I am glad that you liked the article!
Mohammad Azam azamsharp@gmail.com www.gridviewguy.com videos.gridviewguy.com
Houston, TEXAS
|
|
|
|
 |
 | Problem with RowDataBound event in VB jonefer | 13:03 31 Aug '07 |
|
 |
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") + "')"); } }
For me, it looks like this: Protected Sub gvCC_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvCC.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then Dim l As LinkButton = DirectCast(e.Row.FindControl("LinkButton1"), LinkButton) l.Attributes.Add("onclick", "javascript:return " + "confirm('Are you sure you want to delete this record " + DataBinder.Eval(e.Row.DataItem, "DelCCID") + "')")
End If
End Sub
The IDE does not generate an error, however when I run it I get the following error: Conversion from string "javascript:return confirm('Are y" to type 'Double' is not valid.
I've tried adding a single quote to the end of the confirm, and I've even tried removing them. Any idea what is wrong?
|
|
|
|
 |
|
 |
This is probably a little to late to help the poster, but for anyone else who encounter something like this, I recommend using String.Concat() for string concatenation.
It works like this:
String.Concat("string 1 ", strVal2, " string 3.")
In this case, you could do something like:
l.Attributes.Add("onclick", _ String.Concat( _ "javascript:return ", _ "confirm('Are you sure you want to delete this record ", _ DataBinder.Eval(e.Row.DataItem, "DelCCID").ToString(), _ "')" _ ) _ )
Hope this helps! Spiff
|
|
|
|
 |
 | Thank You Great Job Mahesh.J | 20:46 24 Aug '07 |
|
 |
Hi.. Your code example is very good.
Reagrds Mahesh.J
|
|
|
|
 |
 | Thank you zarchi | 2:29 26 Jun '07 |
|
|
 |
 | It works perfectly & thanx alot asankalk | 5:54 6 Jun '07 |
|
 |
I was searching for a better solution of this kind. It helped me alot Thank you!
|
|
|
|
 |
|
|