Tuesday, July 31, 2007

How To Add a Delete Confirmation to a DataGrid

The DataGrid control allows developers to easily display data to end users. Often times the list which is displayed allows users to delete a row of data within the DataGrid. To prevent users form inadvertently deleting data a confirmation dialog box can be displayed to the user asking if they "really" want to delete this data. By leveraging the ItemDataBound event of the DataGrid we can easily add this functionality to our DataGrid.
The first step is to create the DataGrid to display the data. For this example we'll create a template column with a LinkButton which will allow users to delete the data and a Label control to display information about the record.
<asp:DataGrid id="myDataGrid" runat="server">
      <asp:linkbutton id="DeleteLink" runat="server" text="Delete" commandname="Delete" />
      <asp:Label id="myLabel" runat="server" text="<%# DataBinder.Eval(Container.DataItem, "myColumn")%>" />
Next we need to add an event handler for the ItemDataBound event of the DataGrid by identifying the method that will handle the event in the OnItemDataBound property of the DataGrid.
<asp:DataGrid id="myDataGrid" OnItemDataBound="myDataGrid_OnItemDataBound" runat="server">...</asp:datagrid>
The second parameter passed into the event handler for the ItemDataBound event is of the DataGridItemEventArgs type. This parameter gives us access to each item within the DataGrid as data is bound to it through its Item property. Once we have access to the particular item we can find child controls such as our delete LinkButton with the e.Item.FindControl method. Now that we know how to get access to our LinkButton control, we can use its Attributes collection to add an attribute for the onClick of the LinkButton. After casting our returned child control to the proper type we use the Add method of the Attributes collection to add the confirmation dialog box to the LinkButton.
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 wish to delete this item?');");

Now, when we click on our delete link we'll get a confirmation dialog box asking if we are sure we want to delete the item.

Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when.