8

我想循环通过 DataGridViewRowCollection 或 DataGridViewSelectedRowCollection(用户选择)。我不知道如何以简单的方式做到这一点。这是我的代码:

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)
{
    //...
}
4

3 回答 3

8

您可能需要Enumerable.Cast方法。

  List<DataGridViewRow> lst = dataGridView1.Rows.Cast<DataGridViewRow>().ToList();
于 2012-11-24T11:53:35.150 回答
6
DataGridViewSelectedRowCollection rows = MyDataGridView.SelectedRows;               
foreach (DataGridViewRow row in rows)
{
  DataRow myRow = (row.DataBoundItem as DataRowView).Row;
  // do something with your DataRow
}
于 2012-11-24T12:21:30.850 回答
0

您可以创建一个简单的数组并使用两个集合的 CopyTo 方法...

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.

当然它们都是 System.Windows.Forms.BaseCollection,你也可以使用 BaseCollection 的方法......

BaseCollection data=<your condition>?dvgResults.Rows:dvgResults.SelectedRows;
//Just enumerate through BaseCollection..
于 2018-07-30T13:06:58.410 回答