Monday, March 20, 2006

VS: Ask user to confirm delete of record

Using a grid with a delete button, you often want the user to confirm the delete action. This is how to do it:

In VS 2005 add this to your button:
OnClientClick="return confirm('Are you sure you want to delete this record?');"
In VS 2003 add this to your button
OnClick="return confirm('Are you sure you want to delete this record?');"

Or bind it in code:

protected void myDataGrid_OnItemDataBound(object sender, DataGridItemEventArgs e)
{
if(e.Item.FindControl("DeleteLink") != null)
{
((LinkButton) e.Item.FindControl("DeleteLink")).Attributes.Add
("onClick", "return confirm('Are you sure you want to delete this record?');");
}
}

When the user presses the button it receives a messagebox with the text. When the user presses OK the server event is called. When the user presses Cancel, nothing happens.

No comments: