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 に答える