5
votes

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 ?

3
Row collection based on Selected cells ? Can you expand a bit on that, Coz there is a SelectedCells collection not sure if you are looking for the same ? - V4Vendetta

3 Answers

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

foreach(DataGridViewCell cell in dataGridView.SelectedCells)
{
    rowCollection.Add(dataGridView.Rows[cell.RowIndex];
}
8
votes

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();
6
votes

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();