문제

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;
            }
        }
도움이 되었습니까?

해결책

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;
    }
}

다른 팁

Try placing the logic in a CellMouseUp event handler as the CellClick event is occurring before the CheckBox state has been updated.

This along with using the EditedFormattedValue property (which contains the current, formatted value of the cell) to retrieve the CheckBoxes current state.

From MSDN:

The Value property is the actual data object contained by the cell, whereas the FormattedValue is the formatted representation of this object.

It stores the the current, formatted value of the cell, regardless of whether the cell is in edit mode and the value has not been committed.

Here is a working example.

void dataGrid_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex == 0 && e.RowIndex != -1)
    {
        DataGridViewCheckBoxCell checkBoxCell =
            dataGrid.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;

        if (checkBoxCell != null)
        {
            dataGrid.Rows[e.RowIndex].Selected = Convert.ToBoolean(checkBoxCell.EditedFormattedValue);
        }
    }
}

Hope this helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top