Toggle row selection DataGridView, where SelectionMode is FullRowSelect

I have a DataGridView where SelectionMode = FullRowSelect and MultiSelect = False.

When the user clicks on a row, he is selected as expected. However, clicking on the same line again does not deselect the line.

How to make a row selection for switching between selected and unselected?

+5
source share
1 answer

As far as I know, there is no functionality that will do this.

I managed to get the effect you are requesting with the following code:

public partial class Form1 : Form
{
    private bool selectionChanged;

    public Form1()
    {            
        InitializeComponent();
    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (!selectionChanged)
        {
            dataGridView1.ClearSelection();
            selectionChanged = true;
        }
        else
        {
            selectionChanged = false;
        }
    }

    private void dataGridView1_SelectionChanged(object sender, EventArgs e)
    {
        selectionChanged = true;
    }

}

This uses the dataGridView SelectionChanged and CellClick events, as well as a class level variable containing the selection state.

+4

All Articles