我的数据库中有数据,当我选择一行并右键单击它然后单击“删除”时,所有具有相同StudentNo的行都会从datagridview和数据库中删除。我想要的是只有选定的行从数据库和datagridview中删除。附件是我的数据的图像。
这是我的代码。
Try
If Me.DataGridView1.Rows.Count > 0 Then
If Me.DataGridView1.SelectedRows.Count > 0 Then
Dim intStdID As Integer = Me.DataGridView1.SelectedRows(0).Cells("StudentNO").Value
'open connection
If Not myconnection.State = ConnectionState.Open Then
myconnection.Open()
End If
'delete data
Dim cmd As New SqlCommand
cmd.Connection = myconnection
cmd.CommandText = "DELETE FROM AlevelGeneralResults WHERE StudentNO=" & intStdID
Dim res As DialogResult
res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res = Windows.Forms.DialogResult.Yes Then
cmd.ExecuteNonQuery()
Else : Exit Sub
End If
'refresh data
refreshdgv()
'close connection
myconnection.Close()
End If
End If
Catch ex As Exception
End Try
答案 0 :(得分:1)
您可以在SQL中使用更多条件来使Row唯一。
首先,我会添加Columns Subject和BOTP1。
你的SQL看起来像这样:
DELETE FROM AlevelGeneralResults WHERE StudentNO=" & intStdID & " AND Subject='" & strSubject & "' AND BOTP1=" & intBotp
在必须在intStdID
旁添加两个新变量之前Dim intStdID As Integer = Me.DataGridView1.SelectedRows(0).Cells("StudentNO").Value
Dim strSubject As String = Me.DataGridView1.SelectedRows(0).Cells("Subject").Value
Dim intBotp As Integer = Me.DataGridView1.SelectedRows(0).Cells("BOTOP1").Value
最好的方法是,如果您有一个索引/ ID,可以使您的数据行唯一。但是在您的屏幕截图中没有可见的列,可能是ID。