0

我想要一个带有复选框的列,当用户单击它们时,他们会选择自己的行(突出显示它)。我想出了这段代码,但不能完成这项工作,我该如何解决?

有没有更好的方法来做到这一点?(即使在我“取消选中”复选框后,该行仍保持突出显示)。

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

2 回答 2

1

尝试将逻辑放在CellMouseUp事件处理程序中,因为CellClick事件在 CheckBox 状态更新之前发生。

这与使用EditedFormattedValue属性(包含单元格的当前格式化值)一起检索 CheckBoxes 当前状态。

来自MSDN

Value 属性是单元格包含的实际数据对象,而 FormattedValue 是该对象的格式化表示。

它存储单元格的当前格式化值,无论该单元格是否处于编辑模式并且该值尚未提交。

这是一个工作示例。

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

希望这可以帮助。

于 2011-10-20T22:34:13.257 回答
0

CellMouseUp不适用于空格键的选择。
如果您不必进行“真实”选择,我会在单元格值更改时更改行背景颜色,这会容易得多:

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;
    }
}
于 2011-10-20T22:44:10.140 回答