2013-03-04 14 views
6

Jak można naprawić ten błąd:Jak naprawić Index Out Of Range error

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

W tym kodzie:

dataGridView1.AllowUserToAddRows = false; 
dataGridView1.Columns.Add("ID", "ID"); 
dataGridView1.Columns.Add("Firstname", "Firstname"); 
dataGridView1.Columns.Add("MI", "MI"); 
dataGridView1.Columns.Add("Lastname", "Lastname"); 
dataGridView1.Columns.Add("Username", "Username"); 
dataGridView1.Columns.Add("Rights", "Rights"); 
c.Open(); 
OleDbCommand cmd = new OleDbCommand(); 
cmd.Connection = c; 
cmd.CommandText = "SELECT * From Account"; 
OleDbDataReader reader = cmd.ExecuteReader(); 
while (reader.Read()) 
{ 
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["ID"].Value = reader[0].ToString(); 
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Firstname"].Value = reader[1].ToString(); 
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["MI"].Value = reader[2].ToString(); 
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Lastname"].Value = reader[3].ToString(); 
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Username"].Value = reader[7].ToString(); 
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Rights"].Value  = reader[9].ToString(); 
} 
c.Close(); 
+1

Jaka jest struktura tabeli konto? –

+0

Która linia zgłasza błąd? Jakie są stany runtime obiektów na tej linii? – David

+1

Dlaczego nie korzystać z dataBind? – Pyromancer

Odpowiedz

5

Starasz do wyświetlania danych z bazy danych do datagridview? Dlaczego nie skorzystać z databind?

Zobacz mój przykładowy kod:

string connStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=the directory or the path of your database"; 
string query = "SELECT * From Table Name"; 
using (OleDbConnection conn = new OleDbConnection(connStr)) 
{ 
    using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn)) 
    { 
     DataSet ds = new DataSet(); 
     adapter.Fill(ds); 
     dataGridView1.DataSource = ds.Tables[0]; 
    } 
    conn.Close(); 
} 
+0

@AlfredSanz - co masz na myśli? ds jest "DataSet" – lexter

Powiązane problemy