devxlogo

Adding a confirmation popup for delete buttons defined within templates

Adding a confirmation popup for delete buttons defined within templates

The DataList and DataGrid controls easily allow to add a “Delete” button/hyperlink in your template. When clicked, this button/link raises a DeleteCommand event that you can handle to delete the data item of the parent DataList’s/DataGrid’s row. Here’s an example that shows how to declare two column in a DataGrid, that creates one a delete link, and the other a delete push button:

                                

The in the code-behind file you should handle the control’s DeleteCommand event. While this simple implementation surely works fine, it is not the best result you can get – if the user erroneously clicks the delete button/link, the correspondent data item will be deleted immediately, without an explicit confirmation by the user. Adding a confirmation popup dialog is not a big work however, and it greatly improves the usability. What we have to do is adding some javascript in response of the client-side onClick event. This is done by adding an entry in the control’s Attributes collection, when the DataGrid’s row is created. The code and its comments below explain in detail what is done:

Private Sub DataGrid1_ItemCreated(ByVal sender As Object, _    ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles _    DataGrid1.ItemCreated    ' process data rows only (skip the header, footer etc.)    If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = _        ListItemType.AlternatingItem Then        ' get a reference to the LinkButton of this row,        '  and add the javascript confirmation        Dim lnkDelete As LinkButton = CType(e.Item.Cells(3).Controls(0), _            LinkButton)        lnkDelete.Attributes.Add("onclick", _            "return confirm('Are you sure you want to delete this record?');")                ' get a reference to the Button of this row,        '  and add the javascript confirmation        Dim btnDelete As Button = CType(e.Item.Cells(4).Controls(0), Button)        btnDelete.Attributes.Add("onclick", _            "return confirm('Are you sure you want to delete this record?');")    End IfEnd Sub

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist