views:

910

answers:

2

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.

+3  A: 

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();
Meta-Knight
awesome! +1 and answer. just curious but what would the alternate syntax be? I got tripped up somewhere: int[] rowIndexes = (from sc in this.SelectedCells select sc.RowIndex).Distinct().ToArray(); can you add that to the answer?
tyndall
I edited my answer.
Meta-Knight
Ah ok. Need to read an article or two on LINQ and .Cast<>(). Thanks.
tyndall
A: 
        IEnumerable<int> indexes = (from c in dataGridView1.SelectedCells.Cast<DataGridViewCell>()
                 select c.RowIndex).Distinct();
Michael G