指数超出范围。在VB.NET中必须是非负的

时间:2013-03-21 02:12:02

标签: vb.net-2010

我是新手到这里,我有一个关于(DataGridView删除部分)无法用自己解决的错误,所以来这里请求指导并帮助我请....赞赏你的协助!

LOAD DATA EVENT

     `Public Sub loadtoDGV()
        Dim sqlq As String = "SELECT * FROM chattbl"
        Dim sqlcmd As New SqlCommand
        Dim sqladpt As New SqlDataAdapter
        Dim tbl As New DataTable

        With sqlcmd
            .CommandText = sqlq
            .Connection = conn
        End With

        With sqladpt
            .SelectCommand = sqlcmd
            .Fill(tbl)
        End With

        DataGridView1.Rows.Clear()
        For i = 0 To tbl.Rows.Count - 1
            With DataGridView1
                .Rows.Add(tbl.Rows(i)("ChatConttentID"), tbl.Rows(i)("Title"),   tbl.Rows(i)("ChatContent"), tbl.Rows(i)("ChatDateTime"), tbl.Rows(i)("Username"))
            End With
        Next
        conn.Close()
    End Sub`

发生删除部分错误

    `If conn.State = ConnectionState.Closed Then
        conn.Open()
    End If
    For i = 0 To DataGridView1.Rows.Count - 1
        Dim deletemore As Integer = DataGridView1.SelectedRows(i).Cells(0).Value <------{line occurred error}
        Dim sqlq As String = ("DELETE FROM chattbl WHERE ChatConttentID = " &         deletemore & "")
        Dim sqlcmd As New SqlCommand

        With sqlcmd
            .CommandText = sqlq
            .Connection = conn
            .ExecuteNonQuery()
        End With
    Next

    loadtoDGV()`

1 个答案:

答案 0 :(得分:0)

所以我假设您的应用程序是Windows窗体应用程序并且您正在使用this控件...对不起,如果这个假设不正确。

您的错误可能是因为您用于编写For循环的逻辑:

For i = 0 To DataGridView1.Rows.Count - 1
    Dim deletemore As Integer = DataGridView1.SelectedRows(i).Cells(0).Value <------{line occurred error}

您正在循环遍历DataGridView中的所有行,然后尝试从SelectedRows集合中获取该索引。

我认为你的循环假设在很多时候会出现错误,因为它假定DataGridView中的所有行都被选中(因为这是唯一一次DataGridView和DataGridView.SelectedRows中的项目数相等,使循环工作。

使用以下内容循环浏览选定的行可能会更好:

Dim numSelectedRows = DataGridView1.SelectedRows.Count

For i = 0 to (numSelectedRows - 1)
     Dim deletemore As Integer = DataGridView1.SelectedRows(i).Cells(0).Value

PS。围绕控件选择模式的SelectedRows属性有一些注意事项(请参阅链接中的“备注”部分)。我假设您正在遵循这些警告。