【问题标题】:Index out-of-range error索引超出范围错误
【发布时间】:2013-09-05 20:48:20
【问题描述】:

执行此按钮事件时出现错误:这是我的代码:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Handles Button1.Click

    Try
        ' get the details of the item
        Dim R As Your_pharmacy.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 DGV1.Rows.Count - 1
            If R.barcodeNumber = DGV1.Rows(I).Cells(0).Value Then

                ' item found
                ItemLoc = I
                Exit For

            End If
        Next

        ' if item is not found, add it
        If ItemLoc = -1 Then
            DGV1.Rows.Add(R.barcodeNumber, R.ItemName, R.BuyPrice, R.SellPrice, 1, R.SellPrice)
        Else
            ' if item is already there increase its count
            Dim ItemCount As Long = DGV1.Rows(ItemLoc).Cells(4).Value
            ItemCount += 1
            Dim NewPrice As Decimal = R.SellPrice * ItemCount
            DGV1.Rows(ItemLoc).Cells(4).Value = ItemCount
            DGV1.Rows(ItemLoc).Cells(5).Value = NewPrice
        End If

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



        ' compute the total for the recipt
        Dim Sum As Decimal = 1
        For I = 0 To DGV1.Rows.Count - 1
            Sum += DGV1.Rows(I).Cells(5).Value 'here the error happens
        Next

        TextBox4.Text = Sum

    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Error")
    End Try
End Sub

错误详情:

错误:索引超出范围。必须为非负数且小于 集合的大小。参数名称:index vb.net

【问题讨论】:

  • 你在哪条线上?

标签: vb.net indexing


【解决方案1】:

DGV1 的单元必须少于 5 个。发生错误时,使用断点和调试监视窗口查看 DVG1(I) 中有多少单元。也许第一个是用零单元格创建的?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2016-04-17
    • 2015-07-13
    • 2015-02-13
    相关资源
    最近更新 更多