【问题标题】:Datagrid checkbox column select not working right数据网格复选框列选择无法正常工作
【发布时间】:2011-10-20 21:58:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# select datagrid datagridviewcheckboxcell


    【解决方案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);
            }
        }
    }
    

    希望这会有所帮助。

    【讨论】:

    • 谢谢,它可以工作,但我还希望其他选中的行保持选中状态,我该怎么做?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-04-19
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      相关资源
      最近更新 更多