What is the cleanest way to ask a DataGridView to return "indexes of rows that have selected cells"? This is not the same as DataGridView.SelectedRows. I don't allow Row or Column selection. So users must select blocks of cells. I just need to find out which rows have selected cells in them.
Is there some clever lambda expression I should be using? What would you do?
If this helps: In the code I am writing I have already inherited from DataGridView and I'm in my own custom class DataGridViewExt.
LINQ solution:
var rowIndexes = dgv.SelectedCells.Cast<DataGridViewCell>()
.Select(cell => cell.RowIndex)
.Distinct();
Edit:
You were just missing the Cast. It's needed because DataGridViewSelectedCellCollection doesn't implement a generic IEnumerable<DataGridViewCell>
, just IEnumerable
, so when you enumerate the values, they are of type Object
. With the cast, that would give:
int[] rowIndexes = (from sc in this.SelectedCells.Cast<DataGridViewCell>()
select sc.RowIndex).Distinct().ToArray();
IEnumerable<int> indexes =
(from c in dataGridView1.SelectedCells.Cast<DataGridViewCell>()
select c.RowIndex).Distinct();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With