Javascript before asp:ButtonField click

Pablo Fernandez picture Pablo Fernandez · Oct 20, 2008 · Viewed 28.6k times · Source

I have a GridView control in an Asp.net application, that has a <asp:buttonField> of type="image" and CommandName="Delete".

Is there any way to execute a piece of javascript before reaching the OnRowDelete event?

I want just a simple confirm before deleting the row.

Thanks!

EDIT: Please Note that <asp:ButtonField> tag does not have an OnClientClick attribute.

Answer

steve_c picture steve_c · Oct 20, 2008

I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command.

On either of those buttons I would then use the OnClientClick property to execute the JavaScript confirm dialog prior to this.

<script type="text/javascript">
   function confirmDelete()
   {
       return confirm("Are you sure you want to delete this?");
   }
</script>

...

<asp:TemplateField>
  <ItemTemplate>
     <asp:ImageButton ID="DeleteButton" runat="server"
        ImageUrl="..." AlternateText="Delete" ToolTip="Delete"
        CommandName="Delete" CommandArgument='<%# Eval("ID") %>'
        OnClientClick="return confirmDelete();" />
  </ItemTemplate>
</asp:TemplateField>