Wednesday 2 July 2008

GridView - Delete Button

Here's an example of adding a Delete Button to a GridView control.

Ok so let's say you have a DataTable of Contacts bound to a GridView control called gvContacts.
Your DataTable has three column contactID,firstname, lastname.

'The Grid


> DataKeyNames="contactID"< AutoGenerateColumns="false"
<columns>
<asp:boundfield datafield="Contact" headertext="firstname">
<asp:templatefield headertext="firstname">
<itemtemplate>
<asp:label id="firstname" runat="server" text="'<%#">'></asp:Label><
</itemtemplate><
</asp:TemplateField><
<asp:templatefield headertext="lastname"><
<itemtemplate><
<asp:label id="lastname" runat="server" text="'<%#">'></asp:Label><
</itemtemplate><
</asp:TemplateField><
<asp:templatefield headertext="Delete"><
<itemtemplate><
><asp:button commandname="Delete" id="btnDelete" text="Delete Contact" commandargument=" runat="server" />
</itemtemplate><
</asp:TemplateField><
</columns><


'The Row Deleting Event is the bit that actually does the delete operation

Protected Sub gvContacts_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvContacts.RowDeleting

Dim contactID As Integer = Me.gvContacts.DataKeys(e.RowIndex).Value
DeleteContact(ContactID)

End Sub

'Here we add a clientside confirmation script to be kind to the user. When the Delete button is clicked an alert is triggered asking the user
' if they are sure they want to delete the record.

Protected Sub gvContacts_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvContacts.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim b As Button = e.Row.FindControl("btnDelete") 'CType(e.Row.Cells(4).Controls(0), Button)
b.OnClientClick = String.Format("return confirm('Please confirm you wish to delete this record ?');")
End If

End Sub

No comments: