索引超出了datagridview vb.net的限制

时间:2016-07-14 10:28:56

标签: vb.net

我在使用VB.NET中的Access数据库填充DataGridView时遇到问题;这是代码:

Sub loadcreadit()    
    Try
        DataGridView1.Rows.Clear()
        Dim dt As DataTable = New DBConnect().selectdata("SELECT  items.ClientName, items.ClientAddress, items.ClientPhone, items.ClientCredit FROM items;")
        For i As Integer = 0 To dt.Rows.Count - 1
            DataGridView1.Rows.Add()
            DataGridView1(0, i).Value = i + 1
            DataGridView1(1, i).Value = dt.Rows(i)(0).ToString
            DataGridView1(2, i).Value = dt.Rows(i)(1).ToString
        Next
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    End Sub     

当我点击按钮时,我会收到一个异常,并显示错误消息:

  

L'indexétaithorslimites .Il ne do paspasètrenégatifetdoitétreinpieieuràlataille de la collection。 Nonduparamètre:index (翻译)指数超出限制。它不能是负数,必须小于集合的大小。无参数:索引

1 个答案:

答案 0 :(得分:0)

使用DataGridView1.Rows.Add方法传递数据,并确保您有3列:

Sub loadcreadit()
    Try
        Dim dt As DataTable = New DBConnect().selectdata( _
              "SELECT ClientName, ClientAddress, ClientPhone, ClientCredit FROM items;")
        ' make sure you have at least 3 columns
        DataGridView1.Rows.Clear()
        For i As Integer = 0 To dt.Rows.Count - 1
            DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1))
        Next
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub