Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Intermediate
Feb 24, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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:

<asp:DataGrid runat="server" ...>
        <asp:ButtonColumn Text="Delete" CommandName="Delete" />
        <asp:ButtonColumn Text="Delete" ButtonType="PushButton" CommandName= _
            "Delete" />
        <!-- other databound/template/button columns here... -->
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 _
    ' 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), _
        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 If
End Sub
Marco Bellinaso
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date