Search code examples
c#selectdatagriddatagridviewcheckboxcell

Datagrid checkbox column select not working right


I want to have a column with checkboxes that when ever the user clicks them, they select their own row (hightlight it). I have come up with this code, with does not do the job, how can I fix it?

Is there a better way of doing this? (The row stays highlighter even after I "uncheck" the checkbox).

 private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex != -1) 
            {
                if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == true)
                    dataGrid.Rows[e.RowIndex].Selected = false;
                else if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == false)
                    dataGrid.Rows[e.RowIndex].Selected = true;
            }
        }

Solution

  • CellMouseUp will not work for selection with SPACE press.
    If you don't have to do "real" selection, I'd change row background color on cell value change, it'd be much easier:

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex != -1)
        {
            if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[0].Value) == true)
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue;
            else if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[0].Value) == false)
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
        }
    }