在vb.net中插入和更新,访问索引超出范围

时间:2015-03-16 15:05:08

标签: vb.net ms-access

我有应用我希望它做 1-插入第一个语句。 2 - 获取发票的(maxid) 3 - 使用Id插入发票的详细信息。 它给了我这个错误 指数超出范围。

Private Sub insert()
    Dim invoiceday As Date = Today
    Dim userid As Integer
    Dim clientid As Integer
    Dim note As String
    If clients.Visible = True Then
        userid = 1
        clientid = 2
        note = "cash"
    Else
        userid = 2
        clientid = 6
        note = "credit"
    End If
    Dim query1 As String = " insert into invoices([purchasedate],clientid,[Note],userID,total,disq) Values  ( '" & CDate(invoiceday) & "','" & clientid & "','" & note & "','" & userid & "','" & totalprice.Text & "','" & txtdis.Text & "')"
    samselect2(query1)
    Dim maxinvoice As Integer
    maxinvoice = invoiceid()

    For Each row As DataGridViewRow In dvsale.Rows
        Dim query As String = " insert into invoicede(invoiceid,barcode,doaname,Qty,Price,qtyprice)  Values ('" & maxinvoice + 1 & "','" & row.Cells("barcode").Value & "','" & row.Cells("doaname").Value & "','" & row.Cells("qty").Value & "','" & row.Cells("price").Value & "','" & row.Cells("tqty").Value & "')"

        samselect2(query)
    Next

End Sub

这是samselect2的类

 Public Sub samselect2(ByVal sql As String)
        Try
            con.Open()
            With cmd
                .Connection = con
                .CommandText = sql
            End With

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try
        con.Close()
        da.Dispose()
    End Sub

和invoiceid最大数量

Private Function invoiceid()
        checkConnection()
        Dim strQ As String = "SELECT max(invoiceID)as MaxIDbatch  from invoices "
        Dim cmdQ As OleDbCommand = New OleDbCommand(strQ, con)
        Dim result = cmdQ.ExecuteScalar()
        If result IsNot Nothing Then
            Dim x As Integer = 0
            Return x
        Else
            Return result
        End If


    End Function

1 个答案:

答案 0 :(得分:0)

虽然我不完全理解你的问题,但我注意到一些事情:1)似乎InvoiceID不是一个自动递增的身份字段,它可能应该是。 (看看“Is Identity”。)如果是,你可以插入并指定除了那个之外的所有字段,并且数字会自动增加。 2)在你的for ... each中,你通过循环每次迭代都不会增加maxinvoice。虽然您使用的是maxinvoice + 1,但每次仍然是相同的数字。

但是,如果您将InvoiceID设为身份字段,那么所有这些都是不必要的。