Sunday, January 25, 2009

How to Add Confirmation Dialog on the Delete Button in a GridView

I have searched and visited a lot of code on adding confirmation dialog on the Delete control in a GridView in ASP.NET. Among those I found the code snippet below very easy and small.

Write the code below on the RowDataBound event of the GridView.

Assuming that the DeleteButton's type is LinkButton and the it is in the first column( the index of column is 0).
--------------------Code Starts-------------------------
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[0].Controls[0]).Attributes["onClick"] = "if(!confirm('Are you sure to delete this row?'))return false;";

// If DeleteButton's type is Button, you can use (Button) in stead of (LinkButton).
}
}
}

-------------------Code Ends-------------------------------