-2

我有 5 列,我必须删除我的数据库中已经存在的行,以便我的数据库中不存在的剩余行准备好插入到数据库中。但我仍然有一个错误索引超出范围。必须是非负数且小于集合的大小。参数名称:索引..

问题是即使 datagridview 的最后一行已经到达,for next 循环也不会结束。

我已将 allowusertoaddrows 的属性设置为 false ..

这是我的代码..

Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
        Dim rctr, x As Integer

        Dim con As SqlConnection = New SqlConnection("Server=ITS-CODER02\DIBMART; Initial Catalog = HiKLotMgt; User Id= sa; Password = evadkram!@#;")
        con.Open()

        For x = 0 To gridhik.Rows.Count - 1

            cerlotno = gridhik.Item(2, x).Value
            sqlexist = "Select * from tblHikLotMgtDB where CeramicLotNo = '" & cerlotno & "'"
            Dim cmd1 As SqlCommand = New SqlCommand(sqlexist, con)
            Dim rdr As SqlDataReader = cmd1.ExecuteReader

            If rdr.HasRows Then
                MsgBox("Ceramic Lot No: " + cerlotno + " already exists and will be deleted.", vbInformation)

                gridhik.Rows.Remove(gridhik.Rows(x))
                x = x - 1
            End If

            rdr.Close()
        Next
        MsgBox("Ready for Saving....", vbInformation)
    End Sub

提前感谢那些提供帮助的人..谢谢....

4

1 回答 1

1

假设网格最初有 10 行,0-9。您正在删除循环中的网格行,这意味着不再存在原来的 10 行,因此最后一行现在是 (8),并且 (9) 不再存在;这就是为什么您的索引超出范围错误。重构您的循环,使其从最后一行开始并结束,即 For x = gridhik.Rows.Count - 1 To 0 step -1

于 2013-08-10T13:48:36.703 回答