Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle DataGridView row selection where SelectionMode is FullRowSelect

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

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

How can the row selection be made to toggle between selected and unselected?

like image 382
Daniel Ballinger Avatar asked Feb 07 '11 02:02

Daniel Ballinger


Video Answer


1 Answers

As far as I know there is no out of the box functionality that will do this.

I managed to get the effect you are asking for 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;
    }

}

That uses the dataGridView's SelectionChanged and CellClick events, along with a class level variable holding the state of the selection.

like image 57
David Hall Avatar answered Oct 06 '22 13:10

David Hall