Author Topic: VB error msg on POS part 3 toturial  (Read 10 times)

laulong79

  • Newbie
  • *
  • Posts: 1
  • Karma: +0/-0
    • View Profile
VB error msg on POS part 3 toturial
« on: June 19, 2017, 09:08:13 AM »
Pls. help to advice, Im facing below error
"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

Here is the script:
   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'get the details of the items
        Dim R As POS.POSDS.ItemsRow = Button1.Tag

        'next search for the barcode in the datagridview
        Dim I As Integer
        Dim ItemLoc As Integer = -1
        For I = 0 To DGV2.Rows.Count = 1
            If R.Barcode = DGV2.Rows(I).Cells(0).Value Then  <----(error at here)

                'item found
                ItemLoc = I
                Exit For

            End If
        Next

        'if item is not found, add it
        If ItemLoc = -1 Then
            DGV2.Rows.Add(R.Barcode, R.ItemName, R.BuyPrice, R.SellPrice, 1, R.SellPrice)

        Else
            'it item already there incrase its count
            Dim ItemCount As Long = DGV2.Rows(ItemLoc).Cells(4).Value
            ItemCount += 1
            Dim NewPrice As Decimal = R.SellPrice * ItemCount
            DGV2.Rows(ItemLoc).Cells(4).Value = ItemCount
            DGV2.Rows(ItemLoc).Cells(5).Value = NewPrice
        End If


        'next clear textbox1 and set focus to it
        TextBox1.Text = ""
        TextBox1.Focus()
    End Sub

mkaatr

  • Administrator
  • Full Member
  • *****
  • Posts: 115
  • Karma: +1/-0
    • View Profile
Re: VB error msg on POS part 3 toturial
« Reply #1 on: June 19, 2017, 08:24:15 PM »
Hello there...

The error message states that you are going beyond the maximum index available. Please check the for loop condition:

        For I = 0 To DGV2.Rows.Count = 1


it should be

        For I = 0 To DGV2.Rows.Count - 1

The way you wrote it I think could be making the program to enter a loop even if there is no row at all.

Yours sincerely

mkaatr