Reputation: 65
So I have this DataGridView
And This code:
if(dataGridView1.SelectedRows.Count > 1)
{
MessageBox.Show("Error: More than one value selected");
return false;
}
It counts correctly to 2 if I have 2 completly selected rows. But I want to check if any cells from 2 different rows or more are selected.
In other words: in my picture my current selection is returning 1 at the moment but i want it to return 2.
Thank you.
Edit after fix: Working code:
if(dataGridView1.SelectedCells.Cast<DataGridViewCell>().Select(c => c.RowIndex).Distinct().Count() > 1)
{
MessageBox.Show("Error: More than one value selected");
return false;
}
Upvotes: 2
Views: 2270
Reputation: 22876
To get the number of rows with selected cells :
int count = dataGridView1.SelectedCells.Cast<DataGridViewCell>()
.Select(c => c.RowIndex).Distinct().Count();
To check if more than one row is selected:
var selectedCells = dataGridView1.SelectedCells;
bool check = selectedCells.Count > 0
&& selectedCells.Cast<DataGridViewCell>().Any(c => c.RowIndex != selectedCells[0].RowIndex);
Upvotes: 6
Reputation: 107
If you have a fairly standard setup where each column is bound to a property of your backing data object, and each row represents one object, the following should work:
dataGridView1.SelectedCells.Select(c => c.Item).Distinct().Count()
This will return the number of items the different cells are bound to. Since each item has one row that binds to it, it will return the count of every row with at least one selected cell.
Upvotes: 1