title: insert and update in vb.net with access index out of range
body: <p>i have application  i want it to do 
  1- insert the first statement .
  2-get the (maxid) of the invoice 
  3-insert the detail of the invoice with the Id .
  it give me this error
  index out of range .</p>
  
  <pre><code>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  ( '" &amp; CDate(invoiceday) &amp; "','" &amp; clientid &amp; "','" &amp; note &amp; "','" &amp; userid &amp; "','" &amp; totalprice.Text &amp; "','" &amp; txtdis.Text &amp; "')"
      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 ('" &amp; maxinvoice + 1 &amp; "','" &amp; row.Cells("barcode").Value &amp; "','" &amp; row.Cells("doaname").Value &amp; "','" &amp; row.Cells("qty").Value &amp; "','" &amp; row.Cells("price").Value &amp; "','" &amp; row.Cells("tqty").Value &amp; "')"
  
          samselect2(query)
      Next
  
  End Sub
  </code></pre>
  
  <p>this the class of the samselect2</p>
  
  <pre><code> 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
  </code></pre>
  
  <p>and the invoiceid max number </p>
  
  <pre><code>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
  </code></pre>