Negative rowIndex problem for new DataGridViewRow
Brady Kelly <[email protected]> Sun, 27 Jan 2008 20:00:34 +0200
| Newsgroups | gmane.comp.windows.devel.dotnet.winforms |
|---|---|
| Message-ID | <[email protected]> |
I create and add a new row to an unbound DataGridView. Then, if I try and
access an item in the Cells collection of the row, as in my commented out
code, I get an index out of range exception, rowIndex. I'm not specifying a
row index, so I assume it is inferring it from the row object, whose
rowIndex property is -1. However, when I access the cell through a row in
the grids Rows collection, I'm happy, as in my other code. Can anyone
explain this behaviour?
The exception:
Specified argument was out of the range of valid values.
Parameter name: rowIndex
The code:
ExportLineRow newRow = new ExportLineRow(); // Derived from
DataGridViewRows.
newRow.ExportLine = newLIne;
newRow.CreateCells(dgvLayout);
dgvLayout.Rows.Add(newRow);
int cx = 1;
foreach (Column o in
newRow.ExportLine.RecordLayout.Columns.Values)
{
int rowIndex = dgvLayout.Rows.Count - 1;
dgvLayout.Rows[rowIndex].Cells[cx].Value = o.ColumnValue;
// TODO Find out why this doesn't work. Why is rowIndex -1?
//DataGridViewCell c = newRow.Cells[cx];
//newRow.Cells[cx].Value = o.ColumnValue;
// Exception thrown here.
cx++;
}
My column indexing is clearly not the problem, as in the following
breakdown, the first snippet works with the same column index that's used in
the second snippet, which failes:
Works:
foreach (Column o in
newRow.ExportLine.RecordLayout.Columns.Values)
{
int rowIndex = dgvLayout.Rows.Count - 1;
dgvLayout.Rows[rowIndex].Cells[cx].Value = o.ColumnValue;
cx++;
}
Doesn't work:
foreach (Column o in
newRow.ExportLine.RecordLayout.Columns.Values)
{
DataGridViewCell c = newRow.Cells[cx];
newRow.Cells[cx].Value = o.ColumnValue;
cx++;
}