8

I want to loop through DataGridViewRowCollection or DataGridViewSelectedRowCollection (users choice). I don't know how I can do it the simple way. Here is my Code:

List<DataGridViewRow> rows = new List<DataGridViewRow>();

if (dr == DialogResult.No)
    foreach (DataGridViewRow row in dgvResult.Rows)
        rows.Add(row);
else if (dr == DialogResult.Yes)
    foreach (DataGridViewRow row in dgvResult.SelectedRows)
        rows.Add(row);

int counter = 1;

foreach (DataGridViewRow row in rows)
{
    //...
}
svick
  • 236,525
  • 50
  • 385
  • 514
it-west.net
  • 383
  • 1
  • 4
  • 8
  • Possible duplicate of [Using DataGridViewRowCollection object in LINQ](http://stackoverflow.com/questions/2648657/using-datagridviewrowcollection-object-in-linq) – KyleMit Apr 11 '16 at 20:29

3 Answers3

9

You may need Enumerable.Cast method.

  List<DataGridViewRow> lst = dataGridView1.Rows.Cast<DataGridViewRow>().ToList();
Adil
  • 146,340
  • 25
  • 209
  • 204
6
DataGridViewSelectedRowCollection rows = MyDataGridView.SelectedRows;               
foreach (DataGridViewRow row in rows)
{
  DataRow myRow = (row.DataBoundItem as DataRowView).Row;
  // do something with your DataRow
}
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
RajEsh
  • 79
  • 1
  • You can also just make changes to the `DataGridViewRow` that will be reflected automatically back to the underlying `DataRow` due to the nature of the `DataGridView`. – gmlobdell Jul 03 '13 at 23:25
0

You can create a simple array and use the CopyTo method of both collections...

DataGridViewRow[] data;
if (<your condition here>) {
  data=new DataGridViewRow[dvgResult.Rows.Count];
  dvgResult.Rows.CopyTo(data,0);
} else {
  data=new DataGridViewRow[dvgResult.SelectedRows.Count];
  dvgResult.SelectedRows.CopyTo(data,0);
}
//Do whatever you want with 'data', it's a simple array now.

Of course they're both System.Windows.Forms.BaseCollection and you may use the methods of BaseCollection, too...

BaseCollection data=<your condition>?dvgResults.Rows:dvgResults.SelectedRows;
//Just enumerate through BaseCollection..
Zztri
  • 91
  • 1
  • 1
  • DataGridViewSelectedRowCollection does derive from BaseCollection. However, DataGridViewRowCollection does not. [DataGridViewRowCollection on MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridviewrowcollection?view=netframework-4.8) [DataGridViewSelectedRowCollection on MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridviewselectedrowcollection?view=netframework-4.8) – SteveB Dec 30 '19 at 17:40