user3310334
user3310334

Reputation:

check how many rows the selection spans DataGridView

DataGridView.SelectedRows

Seems to only count rows that are wholly selected.

If I select multiple cells from e.g. a single column, DataGridView.SelectedRows seems to always return 0 (if there is more than one column).

How do I get the number of rows that the user's selection spans?

Upvotes: 0

Views: 99

Answers (2)

LarsTech
LarsTech

Reputation: 81675

I guess you would have to count them uniquely:

HashSet<int> rowIndexes = new HashSet<int>();
foreach (DataGridViewCell cell in dgv.SelectedCells) {
  if (!rowIndexes.Contains(cell.RowIndex)) {
    rowIndexes.Add(cell.RowIndex);
  }
}

selectedRowCount = rowIndexes.Count;

Upvotes: 1

Ryan Wilson
Ryan Wilson

Reputation: 10765

One way is to iterate each cell of each row and check the .Selected property of a cell, although after posting this I saw LarsTech's answer which is probably more efficient as it only looks at selected cells:

//Variable to hold the selected row count
int selectedRows = 0;
//iterate the rows
for(int x = 0; x < DataGridView.Rows.Count; x++)
{
   //iterate the cells
   for(int y = 0; y < DataGridView.Rows[x].Cells.Count; y++)
   {
        if(DataGridView.Rows[x].Cells[y] != null)
           if(DataGridView.Rows[x].Cells[y].Selected)
           {
              //If a cell is selected consider it a selected row and break the inner for
              selectedRows++;
              break;
           }
   }


}

Upvotes: 0

Related Questions