我想循环遍历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)
{
//...
}
答案 0 :(得分:5)
您可能需要Enumerable.Cast方法。
List<DataGridViewRow> lst = dataGridView1.Rows.Cast<DataGridViewRow>().ToList();
答案 1 :(得分:5)
DataGridViewSelectedRowCollection rows = MyDataGridView.SelectedRows;
foreach (DataGridViewRow row in rows)
{
DataRow myRow = (row.DataBoundItem as DataRowView).Row;
// do something with your DataRow
}
答案 2 :(得分: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..