Introduction
ASP.NET DataGrid allows you to provide select, edit, cancel and delete buttons. These buttons trigger corresponding events on the server side. These buttons are nothing but button controls (link button or push button) with CommandName property set to select, update, cancel or delete.
In this article we will focus on delete command alone. Many times we need to get confirmation from the user about deletion of the record. DataGrid do not provide any inbuilt way to do that.
We will see how to prompt the user to confirm the delete using JavaScript.
The web form
We will create a simple web form that contains a DataGrid which in turn is bound to the Employee table from Northwind database. The grid has a column Delete that triggers the DeleteCommand event handler. When the user clicks on the Delete button he will be prompted for confirmation. If he clicks on "ok" the form is posted as usual else the form will not be posted.
The task of prompting the user is carried out via client side JavaScript.
The Delete button
If you are using VS.NET you can easily add Delete button using the property builder. Note however that this adds a ButtonColumn to the grid. In order to add javascript to a client side event you have to use Attributes collection of the control. The button column do dot have an ID attribute and hence can not be used for this purpose.
Hence, we need to use template column as shown below. Next we need to add the javascript to each and every Delete link button (one per row). We will do that in ItemDataBound event handler.
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
Dim l As LinkButton
Join the conversation! Your thoughts help the community grow.