2
<asp:CommandField ShowDeleteButton="True" />

How can I link a simple jquery method to the delete button which just asks for user confirmation and returns (true or false) if user is sure he want to delete record in gridview or not?

rikket
  • 2,357
  • 7
  • 46
  • 74

1 Answers1

1

You capture the delete buttons for that grid view, and add a confirmation. Also you take care to not overwrite the existing command.

jQuery(document).ready(function() 
{
  // note: the `Delete` is case sensitive and is the title of the button
  var DeleteButtons = jQuery('#<%= GridViewName.ClientID %> :button[value=Delete]');
  DeleteButtons.each(function () {
    var onclick = jQuery(this).attr('onclick');
    jQuery(this).attr('onclick', null).click(function () {
        if (confirm("Delete this record? This action cannot be undone...")) {
            return onclick();
        }
        else
        {
            return false;
        }
    });
  });   
});   

If you place the GridView inside an UpdatePanel then you need to use the pageLoad() for the update (Ver 4+) as:

function pageLoad()
{
      var DeleteButtons = jQuery('#<%= GridViewName.ClientID %> :button[value=Delete]');
      DeleteButtons.each(function () {
        var onclick = jQuery(this).attr('onclick');
        jQuery(this).attr('onclick', null).click(function () {
            if (confirm("Delete this record? This action cannot be undone...")) {
                return onclick();
            }
            else
            {
                return false;
            }
        });
      });   
}

the pageLoad() is run on page load, but also on each ajax update from the UpdatePanel.

Aristos
  • 66,005
  • 16
  • 114
  • 150
  • Hi thanks for your reply, should I put all that code in the head in a script tag type = text/javascript because it is not working? – rikket Jan 04 '13 at 15:07
  • @rikket This code is working, because I am use it. Place it when the page load, or dom is ready (you can use the jQuery ready), and after each UpdatePanel Updates, if you use UpdatePanels – Aristos Jan 04 '13 at 19:21
  • could you please send whole code cause I still was not able to make this code work (not sure where to put it) Thanks! – rikket Jan 04 '13 at 19:39
  • Last question, how can I change dialogue box title? – rikket Jan 04 '13 at 20:25
  • 2
    @rikket Is not possible, only if you use your custom confirmation. Read the question about: http://stackoverflow.com/questions/43955/changing-the-default-title-of-confirm-in-javascript – Aristos Jan 04 '13 at 20:27