Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - DataGridView and SelectedCells - Finding the Row Indexes of Selected Cells

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.

like image 394
BuddyJoe Avatar asked Nov 04 '09 16:11

BuddyJoe


Video Answer


2 Answers

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();
like image 142
Meta-Knight Avatar answered Oct 05 '22 22:10

Meta-Knight


IEnumerable<int> indexes = 
 (from c in dataGridView1.SelectedCells.Cast<DataGridViewCell>()
  select c.RowIndex).Distinct();
like image 24
Michael G Avatar answered Oct 05 '22 22:10

Michael G