GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

I stumbled upon this blog post earlier today that I thought was pretty cool.  It describes a pretty easy way to add confirmation pop-ups for delete command (or update or edit or any other command) using a GridView control, or before any other post-back event in ASP.NET.  It takes advantage of the new "OnClientClick" property that button controls now have in ASP.NET 2.0 -- and which allow you to author client-side event handlers that can fire prior to post-back (you return true or false from these javascript handlers to indicate whether you want the post-back to continue).

The nice thing is that they work with both standard ASP.NET post-backs, as well as the new Ajax XMLHttp post-back support provided by Atlas (where only portions of a page are updated).  It only took me 30 seconds to add this to the todo-application sample I posted last week:

Hope this helps,

Scott

Update: Bertrand has another good post and sample on how to build much richer notification.  Cool stuff!

 

Published Monday, January 2, 2006 2:35 PM by ScottGu

Comments

# re: GridView: Adding Confirmation before Deleting Items (using the OnClickClick property)

Monday, January 2, 2006 7:25 PM by Fabrice
Scott, I think you mean "OnClientClick" in your post's title...

I needed to do the same for a column I add dynamically to a GridView. I added a comment to the original weblog to show how to do this.

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Monday, January 2, 2006 7:27 PM by scottgu
Doh -- good catch on the title snafu. I just updated it -- thx Fabrice!

Scott

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Tuesday, January 3, 2006 11:20 AM by Luciano Evaristo Guerche
Scott,

I have been using Microsoft Visual Web Developer 2005 Express Edition, since the company I work for hasn't bought the Team versions yet. I have done some prototypes and tests and noted GridView has paging, sorting, updating and deleting options but no inserting option available. For inserting, am I forced to use FormView or I just haven't found the right way with the GridView?

Regards,

Luciano Evaristo Guerche
Taboao da Serra, SP, Brazil
guercheLE at hotmail dot com

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Tuesday, January 3, 2006 2:41 PM by RichB
Please understand that in the world of the web (or to be honest any UI paradigm), popups are bad, distracting metaphors. I guess Alan Cooper talks about this at length in one of his books.

Either provide an inline confirmation as a DIV in the main HTML body, or provide an undo (see GMail for the de-facto brilliance).

In general, confirmations are an easy cop-out for the developer resulting in the user doing more work (ie clicking more often). It's a bad idea to treat your users like this ;-)

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Tuesday, January 3, 2006 6:56 PM by scottgu
Hi Rich,

That is a fair criticism. Unfortunately pop-ups are too easy to-do. ;-)

Hopefully people can use the OnClientClick event handler for more user-friendly models as well...

Thanks,

Scott

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Wednesday, May 24, 2006 12:36 PM by Chad
You have to use ItemTemplate for both Edit and Delete buttons to make it work well!

<ItemTemplate>
           <asp:LinkButton Runat="server" CommandName="Edit">Edit</asp:LinkButton>
           <asp:LinkButton Runat="server" CausesValidation="False"
               OnClientClick="return confirm('Are you sure you want to delete this distribution?');"
               CommandName="Delete">Delete</asp:LinkButton>
       </ItemTemplate>
       <EditItemTemplate>  
           <asp:LinkButton CommandName="Update" Text="Update"      
               runat="server"/>      
           <asp:LinkButton CommandName="Cancel" Text="Cancel"  
               runat="server"/>            
       </EditItemTemplate>  

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Sunday, July 30, 2006 1:38 PM by Atul Dravid (dravid_atul@yahoo.com)
Hi, I have tried the Insert Command in gridview by adding command Field. The insert in gridView is possible. What I did is.... 1.Created GridView control 2.Set AutoSelect and AutoUpdate options ON 3.Created the associated DataSource 4.Opened the collections of columns. 5.Added Insert Command after Select and Update options in columns. 6.Added Event handler for command processing. 7.Checked the command if it is Insert then inserted row in table. 8.Change the EditIndex property to inserted row. Only thing I could not achieve is setting focus on the first column of the row which is inserted just by above mechanism.... Yet another thing which I am trying is to have a pop up box for selecting the value from list. I have reached to the point where I can open the popup box and get the value from it usng the LAYER functionaility, only problem I am facing is to position this Layer dynamically... Do you have any idea about it... Thanks, --Atul Dravid

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Sunday, August 6, 2006 2:26 AM by Samiq
thanks man... this really helped me!

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Wednesday, August 30, 2006 4:56 AM by Abbad
Cheers Scott! Another great and simple one. All the best

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Thursday, September 21, 2006 6:11 AM by Fahad
Hi, I have a question, if it fits in this blog. What about when we go to EDIT mode, and we have an and we need to validate the TextBox in EditTemplate on Update? I tried to add onkeyup javascript event with the TextBox, but it fails at compile, because the TextBox in EditTemplate is not visible at Compile Time. Question is at what time I can check that the TextBox is available so that I can bind Javascript with it? I tried OnRowEditing, OnRowUpdating, OnRowCreated events, no luck to find the control. Basically I am trying to Count number of characters in the textbox. I think there should be some event like OnRowEditModeLoaded something becuase OnRowEditing fires when we are not in edit mode completely. Thanks for any help. Fahad

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Wednesday, January 3, 2007 7:12 PM by Eric

This method is fine if your application doesn't use globalization.  The project I'm working on is translated in five languages and we use application resources for all of the text.  So, when I tried to declare:             <asp:LinkButton ID="delete" Runat="server"

               OnClientClick="return confirm('Are you sure you want to delete this record?');"

         CommandName="Delete">Delete

           </asp:LinkButton>, using "return confirm('<%$ Resources:AppResource, Delete_Item>');" this failed.  The fix is to add an attribute to each LinkButton at runtime.              LinkButton linkButton = null;

           for(int i = 0; i < gvDetail.Rows.Count; i++)

           {

               if(gvDetail.Rows[i].Cells[4].Controls.Count > 0)

               {

                   linkButton = gvDetail.Rows[i].Cells[4].Controls[1] as LinkButton;

                   if(linkButton != null)

                   {

                       linkButton.Attributes.Add("onclick", "return confirm('" + Resources.AppResource.Delete_Item + "');");

                   }

               }

           } .  The cell that contains the Delete LinkButton has three controls: a LiteralControl, a LinkButton, and another LiteralControl.  This is why I used index 1 in gvDetail.Rows[i].Cells[4].Controls[1] as LinkButton;

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Thursday, January 11, 2007 5:49 AM by Marcelo

I would like to ask

If i am using a hyperlinkfield for delete action. Coz i need to do more things rather only delete one record.

How to add the confirm box on hyperlinkfield?

Or any other approach ?

# can any body plz help me to solve my problem

Saturday, February 3, 2007 12:40 AM by Rahul

i m working on asp.net. i m a fresher in asp.net. can anybody tell me how to do multiplication in gridview. price is cming frm database and qty which is a textbox in gridview is user input. we have to do multiplication whn user click update button which is below gridview.whn user click on button result(multiplication) displayed in next

column naed total. m using VS 2005 and C#.

plz send me relered code.

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Monday, February 5, 2007 3:14 AM by TheBlueSky

Thanks for the useful info... you saved my time :)

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Friday, February 23, 2007 11:10 AM by Dave

I needed to have a confirmation as well, only I wanted to make it in the form of a check box where if it is checked, it will delete without asking otherwise the button does nothing.

I just converted the delete button to a template field and handled the OnClick action for it.  Then in the handler if the checkbox isn't checked, I cast the sender to a LinkButton and change its command name to something other than delete:

   Protected Sub deleteLink_Click(ByVal sender As Object, ByVal e As System.EventArgs)    

       If confirmDelete.Checked = False Then

           CType(sender, LinkButton).CommandName = "whatever"

       Else

           CType(sender, LinkButton).CommandName = "Delete"

           confirmDelete.Checked = False

       End If

   End Sub

Kind of a hack, but it does exactly what I was looking for.  Hope this helps someone!

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Tuesday, February 27, 2007 2:48 AM by ScottGu

Thanks for the suggestion Dave!

Scott

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Wednesday, February 28, 2007 11:51 AM by Brian

Scott

If you're using a default gridview delete button and injecting the javascript at runtime, there's a bit of a gotcha. Just doing return confirm("xx"); will always result in the javascript triggered postback for the button being skipped. What's needed is

b.OnClientClick = "if (!confirm('Are you sure that you want to delete this widget?')) return;";

This then gets concatenated when the page is rendered as follows:

onclick="if (!confirm('Are you sure that you want to delete this widget?')) return;BLOCKED SCRIPT__doPostBack('ctl00$ContentPlaceHolder1$BuyGridView','Delete$0')"

Thanks for the great blog, it's been a great resource for me learing .NET!

Cheers

Brian

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Saturday, March 3, 2007 9:37 PM by ScottGu

Hi Brian,

Good catch - thanks for the suggestion!

Scott

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Sunday, March 4, 2007 7:37 PM by Nicky

Hi,

   I'm using c# and I need to know, if i want to redirect in another page when i clicked at Cancel of comfirmation.What should I do?

Hope someone can hekp me.

Thanks a lot.

Nicky

# re: GridView: Adding Confirmation before Deleting Items (using the OnClientClick property)

Wednesday, March 14, 2007 1:03 PM by Raquel

Brian, thanks for this:  I couldn't figure out why the javascript was never returning anything, that was it!