问题
I have a DatagridView control on a Windows form. It's selectionMode property is set to CellSelect.
I want to operate on DatagridViewRow based on selected cells. The DataGridView control is bound to a DataSource.
How to get the Row collection based on selected cells ?
回答1:
List<DataGridViewRow> rowCollection = new List<DataGridViewRow>();
foreach(DataGridViewCell cell in dataGridView.SelectedCells)
{
rowCollection.Add(dataGridView.Rows[cell.RowIndex];
}
回答2:
The answer provided as Linq does not work with the syntax provided. Datagridview does not support ienumerable so you have to use:
IEnumerable<DataGridViewRow> selectedRows = dgPOPLines.SelectedCells.Cast<DataGridViewCell>()
.Select(cell => cell.OwningRow)
.Distinct();
回答3:
DataGridView.SelectedCells
will give you the list of cells that are selected. Each of the DataGridViewCell
instances in that collection has an OwningRow
, this allows you to build your own row collection.
For example:
using System.Linq;
IEnumerable<DataGridViewRow> selectedRows = dgv.SelectedCells
.Select(cell => cell.OwningRow)
.Distinct();
来源:https://stackoverflow.com/questions/8921848/how-to-get-rows-collection-based-on-selected-cells-in-datagridview