|
To add a delete button to a datagrid
follows a similar process to adding an edit button.
-
In the datagrid header
-
In the column definitions of the datagrid add another column
-
In the code behind add an event handler for the delete button
-
Add a confirm dialogue to the delete action.
-
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.
|
|
|
|