Thursday, January 24, 2008

Gridview confirm delete

There are two ways I normally use to add confirmation when deleting a record in a gridview:

<asp:gridview id="SearchResults" autogeneratecolumns="false" datakeynames="vbpk_intUserID" runat="server">

<columns>

<asp:hyperlinkfield datatextfield="strEmail" datanavigateurlfields="strEmail" datanavigateurlformatstring="mailto:{0}" headertext="Email" target="_blank" />

<asp:commandfield buttontype="Button" deletetext="Delete" headertext="Delete" controlstyle-cssclass="btn" showdeletebutton="true" />

</columns>

</asp:gridview>


Private Sub SearchResults_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles SearchResults.RowDataBound

If e.Row.RowType <> DataControlRowType.DataRow Then

Return

End If

Dim lastCellIndex As Integer = e.Row.Cells.Count - 1

Dim deleteButton As Button = DirectCast(e.Row.Cells(lastCellIndex).Controls(0), Button)

deleteButton.OnClientClick = "if (!window.confirm('Are you sure you want to delete this record?')) return false;"

End Sub

Confirm delete for GridView's CommandField using JavaScript



<asp:gridview id="SearchResults" autogeneratecolumns="false" datakeynames="vbpk_intUserID" runat="server">

<columns>

<asp:hyperlinkfield datatextfield="strEmail" datanavigateurlfields="strEmail" datanavigateurlformatstring="mailto:{0}" headertext="Email" target="_blank" />

<asp:TemplateField ItemStyle-HorizontalAlign="center" ItemStyle-Width="50">

<ItemTemplate>

<asp:LinkButton ID="delete" runat="server" Text="Delete" CommandName="delete" CssClass="accountButton"

OnClientClick="return confirmDelete();"/>

</ItemTemplate>

</asp:TemplateField>

</columns>

</asp:gridview>


<script type="text/javascript">

Function confirmDelete()

{

var agree=confirm("Are you sure you wish to delete this record?");

If (agree) Then

return true ;

Else

return false ;

}

</script>

blog comments powered by Disqus