Adding client confirmation to a GridView delete

Onion Blog

Syndication

This question seems to come up quite a bit, so I thought I'd post the solution I prefer for everyone's reference. If you want to add a client-side prompt to a GridView's delete function, so that the user has a chance to say 'no, I didn't mean that!', the simplest way I have found is to add a template field to the GridView with a LinkButton (or plain Button if you prefer) whose CommandName is set to "Delete" and whose OnClientClick property is set to something like 'return confirm("Are you sure???");' - for example:
 
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
   ...
   <asp:TemplateField ShowHeader="False">
     <ItemTemplate>
       <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
                    OnClientClick='return confirm("Are you sure you want to delete this entry?");'
                    Text="Delete" />
     </ItemTemplate>
   </asp:TemplateField>
</Columns>
</asp:GridView>
 
Hope this helps!
 

Limited training time? Need to learn ASP.NET 2.0 and SQL Server 2005?
Come join Fritz Onion and Dan Sullivan the week of July 17, 2006 in Waltham, MA for a
Pluralsight Double Feature: ASP.NET 2.0 and SQL Server 2005
Register today!

 

Posted Mar 22 2006, 01:08 PM by fritz-onion
Filed under:

Comments

Christopher Steen wrote Link Listing - March 22, 2006
on 03-22-2006 6:08 PM
Adding client confirmation to a GridView
delete [Via: Fritz Onion ]
CSLA .NET 2.0 release code available...
Alper Sunar wrote re: Adding client confirmation to a GridView delete
on 03-23-2006 5:42 AM
Speaking of GridView, I have a question about the ShowFooter property if you don't mind. Have you tried setting GridView.ShowFooter property in code behind after DataBind? It does not seem to work. For example when you set it to true, property gets updated but GridView does not display the footer. I was wondering if this is the correct behavior. By the way, I'm using a template column.

Thanks in advance
David Thielen wrote re: Adding client confirmation to a GridView delete
on 04-07-2006 3:55 PM
Wow - this is trivial compared to all the other examples. Thank you
BTE wrote re: Adding client confirmation to a GridView delete
on 04-18-2006 2:06 PM
Very nice example and not a single line of code needed.

Just add a deletecommand to your SQLDataSource and assign a proper DataKey to your grid and it works.
eric fang wrote re: Adding client confirmation to a GridView delete
on 04-20-2006 5:47 PM
Pretty good!! thanx!
Brian ONeil wrote re: Adding client confirmation to a GridView delete
on 05-05-2006 6:48 AM
I would be interested to see an example of this without the CommandName being something standard (Delete, Edit) and without the LinkButton being part of an EditItemTemplate.

I hit this block yesterday and just succombed to using the standard "Delete" commandname.

What if you really need to do something custom to a row like "IncrementColumnInRow" from a LinkButton, with confirmation client side, and without a SQL datasource? Can you access "sender" or something to get the RowIndex where the button click occurred?

Gary vW wrote re: Adding client confirmation to a GridView delete
on 05-15-2006 9:56 AM
Thank you for this! As a newbie I've been fighting this issue and your solution is very clean and simple.
Jørn Schou-Rode wrote re: Adding client confirmation to a GridView delete
on 05-22-2006 3:09 AM
Probably the easiest implementation I have seen to this issue. A bit "hackish" to simply use Delete as CommandName, but indeed it works - thanks!
Raghu wrote An even simpler way
on 07-12-2006 11:13 AM
This is to make the auto generated Delete button by the GridView to have this confirmation. This is a bit hackey .. but the simplest!

No changes in the GridView needed ... no new LinkButton template column required.

Just add this for the RowDataBound event of the GridView ...

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim linkBtn As LinkButton = CType(e.Row.Cells.Item(0).Controls.Item(2), LinkButton)
linkBtn.OnClientClick = "return confirm('Are you sure you want to delete this entry?');"
End If
End Sub

Now "e.Row.Cells.Item(0).Controls.Item(2)" in the code needs to be found out based on the number of Command buttons in the grid. I had the "Delete" command button as the second one .. so. Do change it to suite ur case.

- Raghu
Hans wrote Problem with use of ImageButton
on 08-29-2006 11:20 PM
I try to use a ImageButton instead of a LinkButton as a Delete-command, and I can't get the callback to function with that control.

Can anyone confirm this scenario ?

-Hans
chi wrote re: Adding client confirmation to a GridView delete
on 09-15-2006 12:21 AM
I had the same problem, here is what i did instead at OnClientClick:

OnClientClick="if(!confirm('really delete?')) return;"

it works for me.
Ran wrote re: Adding client confirmation to a GridView delete
on 09-19-2006 5:29 AM
I'm using ImageButton and it's working withou problems. Do you are setting CommandArgument propertly?
Nilesh wrote re: Adding client confirmation to a GridView delete
on 01-07-2007 9:55 PM
hi.
Thank you Its really a Gr8 example.
whichendisup wrote re: Adding client confirmation to a GridView delete
on 03-22-2007 7:17 PM
Great example - thanks!
TRU wrote re: Adding client confirmation to a GridView delete
on 04-05-2007 6:02 PM
Thanks...

Simple! Great for a newbie to .NET
Diego wrote re: Adding client confirmation to a GridView delete
on 04-24-2007 1:52 AM
To confirm any action on a gridview using an imageButton with onclientclick property, you have to set the imagebutton.CausesValidation property to true.

ex.
dbdel.OnClientClick = String.Format("return confirm('Really delete ?');"<gridview_keyvalue"
Pop wrote re: Adding client confirmation to a GridView delete
on 07-08-2007 12:12 AM
IT DOESN'T WORK.
When I click delete, then confirmation pop-up. Then I click "cancel", page is posted back and the record is deleted.
Ashok Parameswaran.K. / Singapore wrote re: Adding client confirmation to a GridView delete
on 08-01-2007 12:24 AM
Its working perfectly.. thanks..
kurt schroeder wrote re: Adding client confirmation to a GridView delete
on 08-08-2007 7:33 AM
thanks, my complex one that adds the event on rowdatabound works no better, but took 10 times the code!
Thanks
alis bina cita wrote re: Adding client confirmation to a GridView delete
on 08-14-2007 2:58 PM
I think that will not work,
it should be:
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
OnClientClick="return confirm('Are you sure you want to delete this entry?');"
Text="Delete" />
remember ASPX is xml, and Xml attribute value should be in double qoutes.
jd wrote does not work
on 11-13-2007 8:46 PM
I had high hopes - sounds great. But when I click Cancel it deletes the record any way.
Scott M. wrote re: Adding client confirmation to a GridView delete
on 11-19-2007 2:53 PM
alis bina cita:

XML does not require the use of double quotes around attribute values, it requires the use of double or single quotes. As long as you end with what you started with, you can use either.
Scott M. wrote re: Adding client confirmation to a GridView delete
on 11-19-2007 2:57 PM
Notes to above posters:

For those of you who found that the record deletes even though you hit cancel: You need to make sure that your wrote the word "return" in front of your confirm method call, without that word, it doesn't matter how you answer the confirm.

For those of you who feel that setting the commandname to "Delete" is a hack: This is not a hack at all, it is how Microsoft knows what internal event you want to fire with your control. It is by design and it is not new.
Jonas W wrote re: Adding client confirmation to a GridView delete
on 11-23-2007 6:47 AM
I really like the simplicity of this solution, however I would like the text to be fetched from resources instead of hacking it into the code.

Any idea on how to get that to work?

I've tried the following:
OnClientClick="return confirm(<%$ Resources: GLOBAL, BTN_REMOVE%>);"
and any version I could come up with...utter failure. Some versions post "<%$ Res..." as the text others just deletes the row without any question.

Cheers!
Henrik L. wrote re: Adding client confirmation to a GridView delete
on 11-27-2007 3:12 AM
Same problem here with text from resource.

What is the solution here ?

On the browser the result is rendered as this:

onclick="return confirm('&lt;%$ Resources: webadmin, EditPartner_ConfirmDeleteText %>');"
Henrik L. wrote re: Adding client confirmation to a GridView delete
on 11-27-2007 3:18 AM
Found the solution with resources.

OnClientClick="<%$ Resources: webadmin, ConfirmDeleteScript %>"

and then resource ConfirmDeleteScript is set to:

return confirm('Er du sikker på at du vil slette denne partner');

All well now :-)
Jonas W wrote re: Adding client confirmation to a GridView delete
on 11-27-2007 6:05 AM
Thx Henrik,

Will try it asap :)

Cheers, Jonas
Lak wrote re: Adding client confirmation to a GridView delete
on 01-10-2008 4:47 AM
Thanks, that is what exactly I am looking for worked well.
D M wrote re: Adding client confirmation to a GridView delete
on 02-03-2008 5:09 AM
Fantastic. I have been looking for a simple solution to this for a while and this is by far the best one ive come across.
Dave wrote re: Adding client confirmation to a GridView delete
on 03-15-2008 7:15 PM
I search for two hours, looked at several ways, pages of code. None of the worked. Found this page and add five lines of code. I worked great. Thanks is not enough.
Rick wrote re: Adding client confirmation to a GridView delete
on 04-21-2008 4:12 PM
good simple solution, hard to believe <CommandField> has no such option.

Thank!
Dave Niven wrote re: Adding client confirmation to a GridView delete
on 05-16-2008 3:56 AM
This solution is by far the best for a gridview row - thanx.
Any simple ideas for when I have a simple Delete button at the bottom of a gridview how to add a Deletion Confirmation. Most of what I have found is long winded.
Dave Niven wrote re: Adding client confirmation to a GridView delete
on 05-16-2008 9:55 AM
Answering my own question, which was solved as a result of this article. If you have a stand alone button you just ensure the asp tags are as follows to achieve the Delete Confirmation

<asp:Button ID="Button1" runat="server" CommandName="Delete" Text="Delete Test" OnClientClick='return confirm("Are you sure you want to delete this entry?");' />

The confirmation occurs and deletion or cancel happens as directed
jones wrote re: Adding client confirmation to a GridView delete
on 06-15-2008 8:16 AM
I have just saved my day!!
Thanks a lot`!!!
Bob wrote re: Adding client confirmation to a GridView delete
on 06-17-2008 6:48 AM
Great article...simple way to do a simple thing but where this is something hard

Many Thanks
grimmy wrote re: Adding client confirmation to a GridView delete
on 08-22-2008 8:27 AM

Adding "OnClientClick='return confirm("Are you sure you want to delete this entry?");' " to the Template control works perfectly for me when using a LinkButton. When using an ImageButton, the confirmation window appears.  But when ever I choose OK to confirm the deletion, I keep getting the message:

"Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. "

Any ideas/suggestions are greatly appreciated. Thanks!

Giribabu wrote re: Adding client confirmation to a GridView delete
on 09-05-2008 7:13 AM

Hi,

dynamically i have created imagebuttons in gridview and added onClientClick event to the imagebutton, when i click on the particular page its redirecting to proper page. but when i click again on any imagebutton, the grid is getting empty without images its showing the grid. can anyone tell how to retain the dynamically created imagebutton when we click on the images more than once.

justme wrote re: Adding client confirmation to a GridView delete
on 09-24-2008 3:24 PM

I was having problems with this as well (cancel didn't abort the delete); this microsoft link explains why - msdn.microsoft.com/.../ms972940.aspx - if your grid button is the command button delete type, it will not work.  it has to be converted to a template button for the onclick event to work as expected.

Neel wrote re: Adding client confirmation to a GridView delete
on 12-02-2008 12:40 PM

Great, if this is this simple why do other examples wasted like two days of my time. I felt like i achived smething. Thanks for your great and simple answer.

Kevin Treacy wrote re: Adding client confirmation to a GridView delete
on 12-03-2008 8:39 AM

Wow, I thought this was going to take a day or two, involve javascript etc. You've sorted in five mins. I owe you big time.

HART wrote re: Adding client confirmation to a GridView delete
on 01-12-2009 4:57 AM

Grimmy, i get the same error as you... no clue on how to fix it. I guess im going to use linkbuttons even if they look horrible...

Liran wrote re: Adding client confirmation to a GridView delete
on 02-02-2009 3:26 AM

You're the BEST

the easiest solution I've seen!!!

tnx a lot

Gerry wrote re: Adding client confirmation to a GridView delete
on 04-15-2009 10:13 PM

It seems that OnClientClick and OnClick cannot both be assigned to an ImageButton and have it function properly. In this case, the page posts-back and the return value from the JavaScript is ignored.

Henry Senior wrote re: Adding client confirmation to a GridView delete
on 06-18-2009 7:15 AM

I didn't want to use a templated control cos I also want to use

EnableSortingAndPagingCallbacks="true" and these two are incompatible.

this is my solution to trap the click event at gridview/table level and see if the event's source element is correct.

           var gridView = document.getElementById('<%=gvCompanies.ClientID%>');

           gridView.onclick = function(e) {

               var returnValue = true;

               var clickElement = (window.event) ? event.srcElement : e.target;

               if (clickElement.tagName.toString().toLowerCase() == 'a') {

                   if (clickElement.innerHTML.match(/delete/i)) {

                       returnValue = confirm('Delete?');

                   }

               }

               return returnValue;

           }

Add a Comment

(required)  
(optional)
(required)  
Remember Me?