Got a solution if anyone is interested:
In order to do this, you will need to call the GetFirstColumn method on
the Columns collection, as this method will take display order into account
(while the iterator will not). You need to follow that up with a call to
GetNextColumn using the previous column. This makes it perfect for an
iterator:
Code:
private static IEnumerable<DataGridViewColumn>GetDisplayOrderEnumeration(DataGridViewColumnCollection columns)
{
// Get the first column.
DataGridViewColumn column = columns.GetFirstColumn(DataGridViewElementStates.None);
// Continue while there is a column.
while (column != null)
{
// Yield the column.
yield return column;
// Get the next column.
column = columns.GetNextColumn(column,DataGridViewElementStates.None, DataGridViewElementStates.None);
}
}
The yield keyword will help create an IEnumerable implementation which
you can use a foreach statement to cycle though. You can use it to get the
name of the column to get the value of from the row:
Code:
for (int r = 0; r <= dgvMain.Rows.Count - 2; r++)
{
foreach (DataGridViewColumn c in GetDisplayOrderEnumeration(dgvMain.Columns))
{
value = dgvMain.Rows[r].Cells[c.Name].Value.ToString();
}
}
The method I gave you will give you an enumeration you can cycle through
to get the rows in the display order, which you can then use to access the
values in the same order in the underlying data source.
Thanks to Nicholas over at the msdn forums.