VJOY
VJOY

Reputation: 3792

How to get rows collection based on selected cells in DatagridView

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 ?

Upvotes: 6

Views: 16413

Answers (3)

Rupert
Rupert

Reputation: 177

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

Upvotes: 10

ColinE
ColinE

Reputation: 70142

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

Upvotes: 6

Haris Hasan
Haris Hasan

Reputation: 30097

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

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

Upvotes: 2

Related Questions