如何根据DatagridView中的选定单元格获取行集合

Vij*_*ade 4 c# datagridview selection winforms

我在Windows窗体上有一个DatagridView控件.它的selectionMode属性设置为CellSelect.
我想基于选定的单元格操作DatagridViewRow.DataGridView控件绑定到DataSource.

如何根据选定的单元格获取Row集合?

小智 7

Linq提供的答案与提供的语法不兼容.Datagridview不支持可数字,因此您必须使用:

        IEnumerable<DataGridViewRow> selectedRows = dgPOPLines.SelectedCells.Cast<DataGridViewCell>()
                                           .Select(cell => cell.OwningRow)
                                           .Distinct();
Run Code Online (Sandbox Code Playgroud)


Col*_*inE 6

DataGridView.SelectedCells将为您提供所选单元格的列表.DataGridViewCell该集合中的每个实例都有一个OwningRow,这允许您构建自己的行集合.

例如:

using System.Linq;

IEnumerable<DataGridViewRow> selectedRows = dgv.SelectedCells
                                               .Select(cell => cell.OwningRow)
                                               .Distinct();
Run Code Online (Sandbox Code Playgroud)

  • 那么同一行可能会多次成为Collection的一部分 (2认同)

Har*_*san 2

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

foreach(DataGridViewCell cell in dataGridView.SelectedCells)
{
    rowCollection.Add(dataGridView.Rows[cell.RowIndex];
}
Run Code Online (Sandbox Code Playgroud)

  • cell.OwningRow 更直接一些。 (3认同)