Pages

Jul 10, 2010

How to show a alert message or confirmation when deleting row from GridView without postback + Asp.Net

This is a basic logic needed in Grid-view while deleting a data. By mistake people may click
on the delete button and if there is no alert or confirmation, some valuable data may be lost.
Let's go for implementation, below is the grid-view


<asp:GridView ID="GridView2" runat="server"  AutoGenerateSelectButton="true"
            DataKeyNames="ID"  AutoGenerateDeleteButton="true"
            onrowdatabound="GridView2_RowDataBound" >
      <Columns>
                <asp:BoundField DataField="ID" HeaderText="SL.No" Visible="false"/>
                <asp:BoundField DataField="Project" HeaderText="Project" Visible="false"/>
      </Columns>
</asp:GridView>

In the above grid the two properties namely AutoGenerateSelectButton,
and AutoGenerateDeleteButton let you show the Select and
Delete button on the GridView.
Now on onrowdatabound event of the GridView we implement the logic like


  protected void GridView2_RowDataBound(object sender,
                                                            GridViewRowEventArgs e)
    {
        // Gets the Delete command column, which is the first column
        foreach (Control control in e.Row.Cells[0].Controls)
        {
            // Gets the Delete link button
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
               DeleteButton.OnClientClick =
               "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }
The above code will show you an alert message before deleting a row.

2 comments:

Anonymous said...

How to show a alert window when deleting column from GridView

asare said...

This is very simple and helpful.
Thanks a lot