vb.net 如何从数据库和datagridview中删除选定的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36738361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete selected row from database and datagridview
提问by Samuel Ronald
i have data in my database, what happens is that when i select a row and right click it and then click delete, all rows having the same StudentNo get deleted from the datagridview and database. what i want is that only the selected row gets deleted from the database and datagridview. attached is an image of my data.

我的数据库中有数据,发生的情况是,当我选择一行并右键单击它然后单击删除时,所有具有相同 StudentNo 的行都会从 datagridview 和数据库中删除。我想要的是只有选定的行会从数据库和 datagridview 中删除。附件是我的数据的图像。

this is the code i have.
这是我的代码。
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
回答by Nik Bo
You could use more criteria in your SQL to make the Row unique.
您可以在 SQL 中使用更多条件来使 Row 唯一。
On the first look I would add the Columns Subject and BOTP1.
乍一看,我会添加列主题和 BOTP1。
Your SQL would look like this:
您的 SQL 将如下所示:
DELETE FROM AlevelGeneralResults WHERE StudentNO=" & intStdID & " AND Subject='" & strSubject & "' AND BOTP1=" & intBotp
Before your must add two new variable beside intStdID
在您必须在 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
The best Way would be if you have an Index/ID which could make your data row unique. But in your screenshot has no visible column which could be the ID.
最好的方法是,如果您有一个索引/ID,可以使您的数据行唯一。但是在您的屏幕截图中没有可见的列可能是 ID。

