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!

 

20 Comments

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

  • Doh -- good catch on the title snafu. I just updated it -- thx Fabrice!



    Scott

  • 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

  • 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 ;-)

  • 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

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

  • 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

  • thanks man... this really helped me!

  • Cheers Scott! Another great and simple one. All the best

  • 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

  • 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: Delete
    , using "return confirm('');" this failed. The fix is to add an attribute to each LinkButton at runtime. LinkButton linkButton = null;
    for(int i = 0; i 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;

  • 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 ?

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

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

  • 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!

  • Thanks for the suggestion Dave!

    Scott

  • 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;javascript:__doPostBack('ctl00$ContentPlaceHolder1$BuyGridView','Delete$0')"

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

    Cheers
    Brian

  • Hi Brian,

    Good catch - thanks for the suggestion!

    Scott

  • 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

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

Comments have been disabled for this content.