从DataGridView和Access数据库中删除错误

时间:2018-11-04 13:46:19

标签: vb.net winforms

我从DataGridView中选择一行以填充文本框,然后单击“删除”按钮以从DataGridView和Access数据库中删除选定的行。我收到ArgumentOutOfRangeException:索引超出范围。必须为非负数,并且小于集合的大小。参数名称:index。错误是针对此行。 Dim custStr As String = dgBartenderLabels.SelectedRows(0).Cells(“ CustNo”)。Value

  Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        Try
            Dim ConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Gwen\Documents\Database1.mdb"
            Dim sqlStr As String
            Dim dt As New DataTable
            Dim cmd As New OleDb.OleDbCommand
            Dim OleDBConn1 As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(ConnStr)
            Dim ds As New DataSet()

            OleDBConn1.Open()
            Dim custStr As String = dgBartenderLabels.SelectedRows(0).Cells("CustNo").Value  'ERROR HAPPENS HERE
            If MessageBox.Show("Do you want to delete?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.Yes Then
                sqlStr = "DELETE FROM TblLabelCustom_copy WHERE [CustNo] =  custStr"
                Dim da As OleDbDataAdapter = New OleDbDataAdapter(sqlStr, OleDBConn1)
                cmd.CommandText = sqlStr
                cmd.ExecuteNonQuery()
            Else
                MessageBox.Show("Deletion aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Warning)

            End If
            dgBartenderLabels.Update()
            OleDBConn1.Close()


        Catch ex As Exception
            MessageBox.Show(ex.ToString)

        End Try
    End Sub

enter image description here

0 个答案:

没有答案