?
2009-03-16 09:40:53 UTC
i want to delte a row of record from datagridview wherein the user presses the delete key and the record gets delete..
now my problem is that the row gets deleted from the datagridview as soon as v press the delete key, and as the control comes to my code, the row is deleted..
so give me a solution wherein i can execute my code before the datagridview deletes the row..
HERE IS MY CODE:
Private Sub Form1_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
If (dggv.SelectedRows.Count = 1) Then
If e.KeyCode.Equals(Keys.Delete) Then
MessageBox.Show("You pressed Delete")
If MessageBox.Show("Are you sure you want to delete this record.", "CAUTION", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = Windows.Forms.DialogResult.OK Then
Dim id As String = Me.dggv.SelectedRows(0).Cells(0).Value
dv = Me.dggv.DataSource
dt = dv.Table
dr = dt.Select("ID=" + id)
If dr.Length > 0 Then
If Me.dggv.SelectedRows.Count > 0 AndAlso Not Me.dggv.SelectedRows(0).Index = _
Me.dggv.Rows.Count - 1 Then
Me.dggv.Rows.RemoveAt(Me.dggv.SelectedRows(0).Index)
End If
Dim ConnectionString = ConfigurationSettings.AppSettings("Connectionstring").ToString()
Dim cnnOLEDB As New OleDb.OleDbConnection(ConnectionString)
Dim cmd As New OleDb.OleDbCommand()
cnnOLEDB.Open()
cmd = cnnOLEDB.CreateCommand()
cmd.CommandText = "DELETE FROM Records WHERE ID =" + id
cmd.ExecuteNonQuery()
cnnOLEDB.Close()
End If
End If
End If
End If
End Sub
AND HERE IS THE CODE WHICH EXECUTES WHEN THE USER CLICKS ON THE DELETE BUTTON CREATED BY ME ON THE FORM:
Private Sub del_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles del.Click
If (dggv.SelectedRows.Count = 1) Then
If MessageBox.Show("Are you sure you want to delete this record.", "CAUTION", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = Windows.Forms.DialogResult.OK Then
Dim id As String = Me.dggv.SelectedRows(0).Cells(0).Value
dv = Me.dggv.DataSource
dt = dv.Table
dr = dt.Select("ID=" + id)
If dr.Length > 0 Then
If Me.dggv.SelectedRows.Count > 0 AndAlso Not Me.dggv.SelectedRows(0).Index = _
Me.dggv.Rows.Count - 1 Then
Me.dggv.Rows.RemoveAt(Me.dggv.SelectedRows(0).Index)
End If
Dim ConnectionString = ConfigurationSettings.AppSettings("Connectionstring").ToString()
Dim cnnOLEDB As New OleDb.OleDbConnection(ConnectionString)
Dim cmd As New OleDb.OleDbCommand()
cnnOLEDB.Open()
cmd = cnnOLEDB.CreateCommand()
cmd.CommandText = "DELETE FROM Records WHERE ID =" + id
cmd.ExecuteNonQuery()
cnnOLEDB.Close()
End If
End If
Else : MsgBox("Please select record to delete", MsgBoxStyle.Critical, "STOP")
End If
End Sub