All select /deselect button

718 Views Asked by At

enter image description hereI want to make n 'all select' button in datagridview. datagirdview has checkbox column. If I press the Select All button, I can select the entire selection. If I press the Select All button again, I want to release the entire selection. I can only Select All, no DeSelect All . Please help me :(

private void Btn_selectall_Click(object sender, EventArgs e)
    {           

        foreach (DataGridViewRow item in dataGridView1.Rows)
        {
            item.Selected = true;
            item.Cells[0].Value = true;
        }
    }
2

There are 2 best solutions below

4
On BEST ANSWER

You could try something like this:

private void Btn_selectall_Click(object sender, EventArgs e)
{
    if (dataGridView1.Rows.Cast<DataGridViewRow>().All(r => r.Selected))
    {
        // deselect all
        foreach (DataGridViewRow item in dataGridView1.Rows)
        {
            item.Selected = false;
            item.Cells[0].Value = false;
        }
    }
    else
    {
        // select all
        foreach (DataGridViewRow item in dataGridView1.Rows)
        {
            item.Selected = true;
            item.Cells[0].Value = true;
        }
    }
}
0
On

You can invert the values like so

item.Selected = !item.Selected;
item.Cells[0].Value = !item.Cells[0].Value;