从DGV上的Access中删除数据

时间:2014-02-13 05:48:32

标签: .net database vb.net datagridview

我正在使用带有来自访问2010的数据绑定项的DGV 但是,我只知道如何删除一个。像这样:

Dim ID = Integer.Parse(dgvMarkers.SelectedRows(0).Cells("colID").Value.ToString())
Dim query = "DELETE FROM tblMarkers WHERE ID = " & ID

如何删除多个选定的条目?
我试过这个,但它似乎没有捕获我选择的所有行,仍然是我点击的最后一行,它是唯一被删除的行。

Dim ID = Integer.Parse(dgvFarrowing.SelectedRows(0).Cells("ID").Value.ToString())
    Dim query As String = "DELETE FROM tblPiglets WHERE ID = " & ID
    Using cmd As New OleDbCommand(query, con)
        For Each r In dgvFarrowing.SelectedRows
            cmd.ExecuteNonQuery()
        Next
    End Using
    MessageBox.Show("Deleted", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)

3 个答案:

答案 0 :(得分:1)

    'Try this.
    'Set first the dgvMarkers.SelectionMode to FullRowSelect

    If dgvMarkers.SelectedRows.Count > 0 Then
        Dim id As New System.Text.StringBuilder

        For Each r As DataGridViewRow In dgvMarkers.SelectedRows
            id.Append(r.Cells("ID").Value.ToString)
            id.Append(",")
        Next

        id.Remove(id.Length - 1, 1) 'remove the last comma

        Dim query = "DELETE FROM tblMarkers WHERE ID IN (" & id.ToString & ")"
    End If

答案 1 :(得分:0)

尝试这样

  If dgvMarkers.SelectedRows.Count > 0 Then
        Dim id as String

        For Each r As DataGridViewRow In dgvMarkers.SelectedRows
           id=r.Cells("ID").Value.ToString & ","
           dgvMarkers.Rows.Remove(r)
        Next

        id=id.Trim(",") 'remove the last comma

        Dim query = "DELETE FROM tblMarkers WHERE ID IN (" & id & ")"
    End If

答案 2 :(得分:0)

构建用于SQL IN()语句的逗号分隔值的另一种方法是使用String.Join函数:

If dgvMarkers.SelectedRows.Count > 0 Then
    Dim ids As New List(Of String)
    For Each r As DataGridViewRow In dgvMarkers.SelectedRows
        ids.Add(r.Cells("ID").Value.ToString)
    Next
    'can use ids directly instead of ids.ToArray() in .NET 4 or above
    Dim query = "DELETE FROM tblMarkers WHERE ID IN (" & String.Join(",", ids.ToArray()) & ")"
End If