barbou barbou - 4 months ago 30
Vb.net Question

Index was out limits datagridview vb.net

I have a problem with populating a

DataGridView
using my Access database in VB.NET; here is the code:

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


When I click on button I get an exception is thrown with an error message:


L'index était hors limites.Il ne doit pas ètre négatif et doit étre inferieur à la taille de la collection. Non du paramètre : index (Translated) Index was out limits. It cannot be negative and must be smaller than the size of the collection. No parameter : index

Answer

Pass the data in the DataGridView1.Rows.Add method and make sure that you have 3 columns:

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   
Comments