David David - 5 months ago 31
Vb.net Question

UltraWinGrid deletes top record rather than the selected one

I've got an ultrawingrid that I can select rows on, and need to be able to delete the highlighted row. At the moment, it calls the database SQL query that I wrote but instead of deleting the record in the row I selected, it deletes the record in the top row instead. Can anybody work out why?

Private Sub btnDeleteIncident_Click(sender As Object, e As EventArgs) Handles btnDeleteIncident.Click

Try
Dim rowValue = ugHistory.Selected.Rows

Dim rowToDelete = ugHistory.Rows(0).Cells(0).Value.ToString

Dim removeIncident As MsgBoxResult
removeIncident = MsgBox("Are you sure you wish to delete this incident?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")

If removeIncident = MsgBoxResult.Yes Then

Database.deleteIncident(rowToDelete)

txtClientSave.Text = ""
rtbProblem.Text = ""
rtbSolution.Text = ""
dtpStart.Value = Date.Today
dtpEnd.Value = Date.Today
dtpStartTime.Value = DateTime.Now
dtpEndTime.Value = DateTime.Now
cboxSolved.Checked = False
btnUpdate.Hide()
btnSave.Show()

ElseIf removeIncident = MsgBoxResult.No Then
loadIncidents()
End If

Catch Ex As Exception
MsgBox("No incidents to delete")
End Try

loadIncidents()

End Sub


Database SQL query;

Public Shared Sub deleteIncident(ByVal supportID As Integer)

Connect()

Dim Dc As New OleDbCommand
Dc.Connection = Con

Dc.CommandText = "DELETE * FROM tblIncidents WHERE([supportID] = " & supportID & ")"

Dc.ExecuteNonQuery()
Disconnect()

End Sub

Answer

You are taking the value for rowToDelete from the first row of the grid not from the current active row

I suggest you to change this line

 Dim rowToDelete = ugHistory.Rows(0).Cells(0).Value.ToString

to

 Dim rowToDelete = ugHistory.ActiveRow.Cells(0).Value.ToString

Also, it is always better to follow a safe approach when handling reference objects like 'ActiveRow', so before running your code add a test for a valid ActiveRow

 if ugHistory.ActiveRow Is Nothing Then 
     Return
 End If
 Dim rowToDelete = ugHistory.ActiveRow.Cells(0).Value.ToString