Reputation: 63
I have a data grid view (dataGridViewPorosity) with 2 columns and I want to insert data from a list (Porosity) to one of this columns, but the exception is: Index was out of range. most be non-negative and less than the size of the collection.
here is my code:
var source = new BindingSource
{
DataSource = Porosity
};
for (int i = 0; i < source.Count; i++)
{
dataGridViewPorosity[1,i].Value = source[i];
}
I saw the similar questions but cannot fix the problem
Upvotes: 1
Views: 1536
Reputation: 106
The DataGridView control works differently from the other tables you might know (or arrays). You need to choose the row and cell. The cell is basically the column.
dataGridViewPorosity.Rows[rowNumber].Cells[cellNumber].Value = source[i];
I assume you want to use the second cell and the row with the i
value. You can do it just like that:
dataGridViewPorosity.Rows[i].Cells[1].Value = source[i];
Good luck!
EDIT: Try to create new rows, like so:
int rownum = dataGridViewPorosity.Rows.Add();
And then use the rownum as the row number you would like to insert your data to.
dataGridViewPorosity.Rows[rownum].Cells[1].Value = source[i];
Of course, these must be in the for loop.
Upvotes: 1