I have a DataGridView with a number of columns and rows. I have MutliSelect enabled, but this allows selection of all cells.
I want to limit the selection vertically, horizontally, full row or full column, but never a mix of both. The user can select by dragging starting at any cell then either vertically or horizontally.
Here's a small diagram to clarify if it helps at all.

Here's the brute force method - when the selection changes, de-select any cells that fall outside the current row/column selection:
int _selectedRow = -1;
int _selectedColumn = -1;
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
switch (dataGridView1.SelectedCells.Count)
{
case 0:
// store no current selection
_selectedRow = -1;
_selectedColumn = -1;
return;
case 1:
// store starting point for multi-select
_selectedRow = dataGridView1.SelectedCells[0].RowIndex;
_selectedColumn = dataGridView1.SelectedCells[0].ColumnIndex;
return;
}
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
if (cell.RowIndex == _selectedRow)
{
if (cell.ColumnIndex != _selectedColumn)
{
_selectedColumn = -1;
}
}
else if (cell.ColumnIndex == _selectedColumn)
{
if (cell.RowIndex != _selectedRow)
{
_selectedRow = -1;
}
}
// otherwise the cell selection is illegal - de-select
else cell.Selected = false;
}
}
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