Paradox
Paradox

Reputation: 129

c# selecting multiple rows in datagridview by checkbox

I have found several related articles and tried them, but couldn't solve the problem. I have a checkbox column in the datagridview of my winForm application. I want to select multiple rows by checking the checkboxes of the adjacant rows and perform some operation on selected rows. But my rows are not getting selected. My code is:

this.dgvLoadTable.CellClick += new DataGridViewCellEventHandler(dgvLoadTable_CellClick);
private void dgvLoadTable_CellClick(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dgvLoadTable.Rows)
        {
            //If checked then highlight row

            if (Convert.ToBoolean(row.Cells["Select"].Value))// Select is the name 
                                                             //of chkbox column
            {
                row.Selected = true;
                row.DefaultCellStyle.SelectionBackColor = Color.LightSlateGray;
            }
            else
                row.Selected = false;
        }
    }

What I'm doing wrong here?

Upvotes: 1

Views: 15107

Answers (1)

You need to handle the CellValueChanged event instead of CellClick one:

private void dgvLoadTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    foreach (DataGridViewRow row in dgvLoadTable.Rows)
    {
        if (row.Cells[3].Value != null && row.Cells[3].Value.Equals(true)) //3 is the column number of checkbox
        {
            row.Selected = true;
            row.DefaultCellStyle.SelectionBackColor = Color.LightSlateGray;
        }
        else
            row.Selected = false;
    }
}

And add the CurrentCellDirtyStateChanged event also:

private void dgvLoadTable_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgvLoadTable.IsCurrentCellDirty)
    {
        dgvLoadTable.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

Upvotes: 2

Related Questions