Datagrid复选框列选择不正常

时间:2011-10-20 21:58:44

标签: c# select datagrid datagridviewcheckboxcell

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

有更好的方法吗? (即使在“取消选中”复选框后,该行也会保持高亮显示。)

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

2 个答案:

答案 0 :(得分:1)

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

这与使用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);
        }
    }
}

希望这有帮助。

答案 1 :(得分:0)

使用SPACE按钮选择

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;
    }
}
相关问题