C# 如何基于DatagridView中的选定单元格获取行集合

C# 如何基于DatagridView中的选定单元格获取行集合,c#,winforms,datagridview,selection,C#,Winforms,Datagridview,Selection,我在Windows窗体上有一个DatagridView控件。它的selectionMode属性设置为CellSelect 我想基于选定的单元格对DatagridViewRow进行操作。DataGridView控件绑定到数据源 如何基于所选单元格获取行集合?DataGridView。SelectedCells将为您提供所选单元格的列表。该集合中的每个DataGridViewCell实例都有一个OwningRow,这允许您构建自己的行集合 例如: using System.Linq; IEnume

我在Windows窗体上有一个DatagridView控件。它的selectionMode属性设置为CellSelect
我想基于选定的单元格对DatagridViewRow进行操作。DataGridView控件绑定到数据源


如何基于所选单元格获取行集合?

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

例如:

using System.Linq;

IEnumerable<DataGridViewRow> selectedRows = dgv.SelectedCells
                                               .Select(cell => cell.OwningRow)
                                               .Distinct();
使用System.Linq;
IEnumerable selectedRows=dgv.SelectedCells
.Select(cell=>cell.OwningRow)
.Distinct();
列表行集合=新列表();
foreach(dataGridView.SelectedCells中的DataGridViewCell单元格)
{
添加(dataGridView.Rows[cell.RowIndex];
}

作为Linq提供的答案与提供的语法不兼容。Datagridview不支持ienumerable,因此您必须使用:

        IEnumerable<DataGridViewRow> selectedRows = dgPOPLines.SelectedCells.Cast<DataGridViewCell>()
                                           .Select(cell => cell.OwningRow)
                                           .Distinct();
IEnumerable selectedRows=dgpolines.SelectedCells.Cast()
.Select(cell=>cell.OwningRow)
.Distinct();

基于所选单元格的行集合?你能在此基础上再扩展一点吗,因为有一个
所选单元格
集合不确定你是否在寻找相同的?cell.OwningRow更直接一点。对。我不知道它的存在。谢谢没有问题。不是你的答案有什么问题,它还是很简单!我不明白这是如何工作的,一个用户在一行中选择了多个单元格,这不是会将同一行添加两次吗?可能会使同一行多次成为集合的一部分
        IEnumerable<DataGridViewRow> selectedRows = dgPOPLines.SelectedCells.Cast<DataGridViewCell>()
                                           .Select(cell => cell.OwningRow)
                                           .Distinct();