Padding Padding
Janet
Systems
 Register  Login 
Telephone  01628 566 178
Website Design, Hosting and Software Services
  Search 
Padding
corner Padding corner
Padding Padding
corner Padding corner
 ASP.NET Articles

To add a delete button to a datagrid follows a similar process to adding an edit button. (See our article here).  To acheive our aim we need to add four bits of code

  1. In the datagrid header
  2. In the column definitions of the datagrid add another column
  3. In the code behind add an event handler for the delete button
  4. Add a confirm dialogue to the delete action.
  5. Ensure that the postback is handled correctly

1. Datagrid Header
The onItemBound and  OnDeleteCommand events needs to be added to the datagrid definition

OnDeleteCommand="mydatagridDelete"
OnItemCreated="myDatagrid_ItemDataBound"

2. OnItemCreatedevent handling code in our code behind page

Sub mydatagridDelete(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
    Try
    myDatagrid.EditItemIndex = -1
        If e.CommandName = "Delete" Then
            Dim mytable_id As Integer = e.Item.Cells(0).Text
            Dim myConnection As SqlConnection
            Dim myCommand As SqlCommand
            Dim myDataReader As SqlDataReader
            Dim strSQL As String
            strSQL = "DELETE FROM mytable WHERE ID=" & mytable_id
            myConnection = New SqlConnection(ConfigurationSettings.AppSettings("MyDSN"))
            myCommand = New SqlCommand(strSQL, myConnection)
            Dim myDataSet As DataSet
            myConnection.Open()
            myDataReader = myCommand.ExecuteReader()
            myConnection.Close()
        End If
        BindmyDatagrid()
    Catch
        msgmyDataGrid.Text = "Error"
    End Try
End Sub 'myDatagridDelete

3. Add the itembound event handler
The first two steps are fine on their own.  However, if someone should click on the delete button in error they will have lost that row of information.  We need to add a confirmation to trap this.

Public Sub myDatagrid_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
    'CType(e.Item.FindControl("Delete"), LinkButton).Attributes.Add("onclick", "return confirm('Are you sure you want to delete this record?');")
End Sub 'myDatagrid_ItemDataBound

It may be that you have already added the itembound event handler, in which case you simply need to add the exra line of code.


This article viewed: 9839 times Back

Copyright © 2004-2007 Janet Systems Ltd.

 Print   

DotNetNuke Website design and hosting from £15.00 per month. More...

Looking for a website design company in the Thames Valley, call us on 01628 566178

DotNetNuke Modules
DotNetNuke Modules availalble from Janet Systems

DotNetNuke Skins
DotNetNukeSkins.gif

from Janet Systems

Padding
Copyright 2002-2008 Janet Systems Ltd.   Terms Of Use  Privacy Statement Tuesday, May 13, 2008