2016-04-20 132 views
0

我在我的數據庫中有數據,會發生什麼情況是當我選擇一行並右鍵單擊它然後單擊刪除時,具有相同StudentNo的所有行都會從datagridview和數據庫中刪除。我想要的是隻有選定的行被從數據庫和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 
+0

首先..更改Me.DataGridView1.SelectedRows(0).Cells(「StudentNO」).Me.DataGridView1.CurrnetRow.Index刪除當前行並更改cmd.CommandText =「DELETE FROM AlevelGeneralResults WHERE StudentNO =「&intStdID,找到記錄Id表單數據庫.. – CristiC777

+0

@ CristiC777,我不太明白這個部分:改變cmd.CommandText =」刪除從AlevelGeneralResults WHERE StudentNO =「&intStdID,找到記錄Id表單數據庫。 –

+0

我認爲你的數據庫設計鏈接中有一個流程來識別來自DGV的每一行,使用DataSet和DataTable更容易,並且綁定到DGV。 – CristiC777

回答

1

你可以在你的SQL中使用更多條件來使行唯一。

在第一次看,我會添加列主題和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。

+0

我的主鍵由StudentNo,Class,Term,Subject和year組成。我已經嘗試過您的解決方案,但它仍然刪除具有相同學號的所有行。 –

+0

@SamuelRonald你想過添加一個獨一無二的ID列嗎?像GUID或連續的數字。有了這個,你只需要搜索這個列並刪除這一行。 –

+0

否則,您必須更改使用主鍵過濾的位置。 '從AlevelGeneralResults刪除WHERE StudentNO =? AND Class ='?' AND Term ='?' AND Subject ='?' AND Year =?' –

相關問題