Limiting cell selection of DataGridView cell to only column or row

I have a DataGridView with multiple columns and rows. I have it enabled MutliSelect

, but this allows all cells to be selected.

I want to constrain the selection vertically, horizontally, full or full column, but never mix them. The user can select by dragging, starting from any cell, then vertically or horizontally.

Here's a small diagram to show if it helps at all.

0MPQj.png

+3


source to share


1 answer


Here's a brute force method - when the selection changes, deselect all cells that fall outside the current row / column:



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;
    }
}

      

+4


source







All Articles