I have a DataGridView which I am populating from a list of objects. However my the 2nd loop through my foreach results in an ArgumentOutOfRangeException.
Here is my code:
foreach (Abonat abonat in list.getAbonati())
{
dataGridView1.Rows[i].Cells[0].Value = abonat.id; //exception occurs here on second loop
dataGridView1.Rows[i].Cells[1].Value = abonat.prenume;
dataGridView1.Rows[i].Cells[2].Value = abonat.nume;
dataGridView1.Rows[i].Cells[3].Value = abonat.adresa;
i++;
}
The first time the foreach runs, everything is fine, it even shows up in the DataGridView, but the 2nd time, I get the exception (actually it says A first chance exception of type ‘System.ArgumentOutOfRangeException’ occurred in mscorlib.dll) and my form is shown, without running the rest of the foreach.
Any help on this? I’ve tried instancing the dataGridView1.Rows[i] = new DataGridViewRow(); but it’s read-only.
You need to create rows before trying to access them;
Then you’ll be able to access them via dataGridView1.Rows[n].Cells[0].Value = x;
Cheers