Monday, December 12, 2011

How to show Confirm message when click Delete button in Gridview

 First of all, you need to know the following javascript methods.

preventDefault method (event) or return false; or returnValue=false;

If an event is cancelable, you can use the preventDefault method and the returnValue property to cancel the event. When an event is canceled, the default action that belongs to the event will not be executed. For example, when the onclick event (the onclick event is cancelable) is canceled for a server control such as button, then clicking on the Button does not occur autopostback.
The properties and methods mentioned above do not affect the propagation of events. If you need to prevent the propagation of an event in the DOM hierarchy or in ajax update panel or in page using master page, use the cancelBubble property and the stopPropagation method.

cancelBubble property (event) or stopPropagation method

When an event can bubble up, you can stop its propagation with the cancelBubble property or the stopPropagation method. Use the stopPropagation method in Firefox, Opera, Google Chrome and Safari, because the cancelBubble property is deprecated in those browsers. Internet Explorer also supports the stopPropagation method from version 9. In Internet Explorer before version 9, use the cancelBubble property, because the stopPropagation method is not supported. 

In .aspx,
//javascript is here.
function DeleteConfirm(e) {
    if (confirm('Are you sure to submit?')) {
        return true;
    else {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
            return false; // or returnValue=false; or e.preventDefault();

 //server control is here.
 <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
        <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False"
            ReadOnly="True" SortExpression="id" />
        <asp:BoundField DataField="title" HeaderText="title" SortExpression="title" />
        <asp:TemplateField HeaderText="View">
                <asp:Button ID="btnDelete" runat="server" CommandArgument='<%# Eval("id") %>'  CommandName="DeleteRow"
                    Text="Delete" />
In code-behind,

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    if(e.CommandName == "DeleteRow")
        // Coding here

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.DataRow)
        Button btn = e.Row.FindControl("btnDelete") as Button;
        btn.OnClientClick = "return DeleteConfirm(this);";
Enjoy the programming!

No comments:

Post a Comment