by Edward
08 May 2010 11:39
Every now and again you might want to use the "delete" or "update" commands from a gridview. However, once you click the button to delete the item from the list or in most cases from the database - you have no safety check. The user might make a mistake, and it can be a costly mistake. An easy way to force the user to think about this action, is to use javascript and ask the user if he/she is sure they want to delete the item.
In the RowDataBound event of the GridView control, you will find the 'Delete' command button control by specifying the cell index. All you have to do is add an 'attribute' to the control, and the "onclick" event. This will trigger a javascript confirmation alert to the user, which asks the user if he/she is sure they want to delete the item. Only when the user confirms the action, will the item be deleted.
Here is a simple example using C# and javascript.
1: if (e.Row.RowType == DataControlRowType.DataRow)
2: {
3: // check for controls in the gridrow cell. Index starts at 0.
4: if (e.Row.Cells[3].HasControls())
5: {
6: LinkButton btnDelete = ((LinkButton)e.Row.Cells[3].Controls[0]);
7: btnDelete.Attributes.Add("onclick",
8: "return confirm('Are you sure you want to delete this item?');");
9: }
10: }
It is important to note that you should always check if the control exists or not. This will be very useful, when the 'Edit' command button is used along with 'Delete' command button.