我在我的數據庫中有數據,會發生什麼情況是當我選擇一行並右鍵單擊它然後單擊刪除時,具有相同StudentNo的所有行都會從datagridview和數據庫中刪除。我想要的是隻有選定的行被從數據庫和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
首先..更改Me.DataGridView1.SelectedRows(0).Cells(「StudentNO」).Me.DataGridView1.CurrnetRow.Index刪除當前行並更改cmd.CommandText =「DELETE FROM AlevelGeneralResults WHERE StudentNO =「&intStdID,找到記錄Id表單數據庫.. – CristiC777
@ CristiC777,我不太明白這個部分:改變cmd.CommandText =」刪除從AlevelGeneralResults WHERE StudentNO =「&intStdID,找到記錄Id表單數據庫。 –
我認爲你的數據庫設計鏈接中有一個流程來識別來自DGV的每一行,使用DataSet和DataTable更容易,並且綁定到DGV。 – CristiC777