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.
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>
I found that the most elegant way to do this is to use jQuery to wire the onClick event:
<script type="text/javascript">
$(".deleteLink").click(function() {
return confirm('Are you sure you wish to delete this record?');
});
</script>
...
<asp:ButtonField ButtonType="Link" Text="Delete"
CommandName="Delete" ItemStyle-CssClass="deleteLink" />
Notice that I use an arbitrary CSS class to identify the link button.
In the GridView
's RowCreated
event handler, use FindControl
to find the named button, and add to the Attributes collection:
btn.Attributes.Add("onclick", "return confirm('delete this record?');");
Your ASP.Net code will only be executed if confirm() is true, i.e. has been ok'd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With