簡體   English   中英

如何從數據庫和DataGridView刪除選定的行

[英]How to delete selected row from database and datagridview

我的數據庫中有數據,發生的情況是,當我選擇一行並右鍵單擊它,然后單擊“刪除”時,所有具有相同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

您可以在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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM