Eduard Luca
Eduard Luca

Reputation: 6602

System.ArgumentOutOfRangeException occurred in mscorlib.dll C#

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.

Upvotes: 1

Views: 30623

Answers (3)

MethodMan
MethodMan

Reputation: 18843

You can not add it this way. For starters it is not know or defined but then you increment it. You can add as many rows you want but you are adding them incorrectly is what we are trying to tell you.

incorrect usage here: dataGridView1.Rows[i].Cells[0].Value = abonat.id;

Upvotes: 0

legrandviking
legrandviking

Reputation: 2414

You need to create rows before trying to access them;

int n = dataGridView1.Rows.Add();

dataGridView1.Rows[n].Cells[0].Value = title;
dataGridView1.Rows[n].Cells[1].Value = dateTimeNow;

Then you'll be able to access them via dataGridView1.Rows[n].Cells[0].Value = x;

Cheers

Upvotes: 4

Rouvé
Rouvé

Reputation: 415

Add the following above your code

dataGridView1.ColumnCount = 4; dataGridView1.ColumnHeadersVisible = true;

Upvotes: 1

Related Questions