view raw
sashoalm sashoalm - 7 months ago 78
C# Question

Enumerate/iterate the rows of a System.Windows.Forms.DataGrid

I'm using System.Windows.Forms.DataGrid instead of DataGridView. I know it's obsolete, but I'm using a custom control that inherits from DataGrid and it is too complicated to be ported to DataGridView without days of work.

I need to iterate through the rows but it doesn't have a

collection, so trying like

DataGrid grid = filterableGrid.EmbeddedDataGrid;
foreach (var row in grid.Rows)
// do stuff

fails with this error:

'DataGrid' does not contain a definition for 'Rows' and no extension method...

So how do I go about iterating it?


You can iterate through rows and columns of DataGrid using the indexer this way:

for (int row = 0; row < grid.VisibleRowCount; row++)
    for (int column = 0; column < grid.VisibleColumnCount; column++)
        var value = grid[row, column];

Also you can use the DataTable which you use as DataSource of DataGrid:

var table = grid.DataSource as DataTable;
foreach (DataRow row in table.Rows)