Friday, November 05, 2010

Client side confirmation in asp:CommandField

When you have an asp.net gridview (framework 3.5) on your page, which includes a column of "asp:CommandField" there is no option to control any client-side behaviour with the designer. I wanted a client side confirmation when a user pressed the delete icon which I placed by asp:CommandField ButtonType="Image" DeleteImageUrl="~/images/del.png" ...

There is a way to add client side confirmation to the asp:CommandField delete action. This is done by injecting javascript into the generated ImageButton in the OnRowDataBound event of the gridview. In the example below, the code loops through all the controls in the last cell of the row (there is where I have the asp:CommandField). If the control is an ImageButton and it has the CommandName "Delete" then set the OnClientClick property to a javascript call.


protected void grdItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells.Count > 1)
{
var ctls = e.Row.Cells[e.Row.Cells.Count - 1].Controls;

foreach (var c in ctls)
if ((c is ImageButton)
&& (((ImageButton)c).CommandName == "Delete"))
((ImageButton)c).OnClientClick =
"if (!window.confirm('Are you sure')) return false;";
}
}

No comments: