Monday, 21 November 2016

Delete Row with Confirmation in asp.net

Delete Row with Confirmation in asp.net

Description:

In this example we explain that how to delete a row from grid view with confirmation message using code behind in asp.net.here we create confirmation dialog from code behind and delete or remove the rows from grid view.

Here we generate the button on click event from code behind and set the confirmation dialog box in asp.net.sometime we have requirement like to delete the rows based on row command button event with confirm dialog box at that time below code is very useful.
Aspx Code:

<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Item" HeaderText="Item" />
        <asp:BoundField DataField="Price" HeaderText="Price" />
        <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
    </Columns>
</asp:GridView>

Aspx.cs Code:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string item = e.Row.Cells[0].Text;
        foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
        {
            if (button.CommandName == "Delete")
            {
                button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
            }
        }
    }
}


0 comments:

Post a Comment