1

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?

1
  • To start, I suggest you use the CellContentClick or CellValueChanged (given that you make sure you're clicking on the Select cell) events. That will make sure you actually click the checkbox and not the surrounding area of the checkbox. Did you try and debug to see if it actually goes into the foreach loop? Commented Nov 11, 2014 at 15:11

1 Answer 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, all of the procedures I have previously tried works fine, including yours. My datagridview was set to readonly, that's why the rows were not getting selected. I am accepting your answer btw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.