Vb.net 如何从数据库和datagridview中删除所选行
我的数据库中有数据,当我选择一行并右键单击它,然后单击“删除”时,所有具有相同StudentNo的行都会从datagridview和数据库中删除。我想要的是只从数据库和datagridview中删除选定的行。附件是我的数据图像。 这是我的密码Vb.net 如何从数据库和datagridview中删除所选行,vb.net,Vb.net,我的数据库中有数据,当我选择一行并右键单击它,然后单击“删除”时,所有具有相同StudentNo的行都会从datagridview和数据库中删除。我想要的是只从数据库和datagridview中删除选定的行。附件是我的数据图像。 这是我的密码 Try If Me.DataGridView1.Rows.Count > 0 Then If Me.DataGridView1.SelectedRows.Count > 0 Then
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
您可以在SQL中使用更多条件使行唯一 在第一次查看时,我将添加列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。首先。。将Me.DataGridView1.SelectedRows(0.Cells(“StudentNO”).Value与Me.DataGridView1.CurrnetRow.Index一起更改为删除当前行,并更改cmd.CommandText=“从AlevelGeneralResults中删除,其中StudentNO=“&intStdID,查找记录Id表单数据库..@CristiC777,我不太了解这部分:change cmd.CommandText=”“从AlevelGeneralResults中删除,其中StudentNO=“&intStdID,从数据库中查找记录Id。我认为您的数据库设计链接中有一个流。”。。要识别每一行。。从DGV,使用DataSet和DataTable更容易。。我的主键由学生号、班级、学期、科目和年份组成。我尝试过你的解决方案,但它仍然会删除所有具有相同学号的行。@SamuelRonald你是否想过添加一个唯一的ID列?例如GUID或连续数字。使用此选项,您只需搜索此列并仅删除此行。否则,您必须使用主键更改筛选位置<代码>从AlevelGeneralResults中删除,其中StudentNO=?Class='?'和Term='?'和Subject='?'和Year=?我已经试过了,而且成功了,我只是不想改变我的主键,但我想我必须使用这个选项。谢谢你的帮助。