有没有办法停止DataGridViewCheckBoxColumn自动检查点击?

时间:2015-09-25 08:43:36

标签: c# datagridview datagridviewcheckboxcell

我正在使用DataGridView并设置了一些DataGridViewCheckBoxColumns,其中两个将ThreeState属性设置为True。

对于网格中的某些行,我只希望复选框为Checked或Indeterminate。应该永远不会为用户提供未选中的操作。但是,如果用户反复单击该复选框,则会从选中复选到不确定。我只是想要检查,不确定,检查,不确定等。

有没有办法在单击时禁止选中/取消选中复选框(类似于标准Windows窗体复选框控件上的AutoCheck属性),或者是否有一个事件我可以用来取消DataGridViewCheckBoxCell的已检查更改?

我试图以编程方式强制将已检查的单元格从未选中状态强制为检查或不确定,但UI从未反映过此。

1 个答案:

答案 0 :(得分:2)

假设您添加的DataGridViewCheckBoxColumn已遵循以下模式:

DataGridViewCheckBoxColumn cbc = new DataGridViewCheckBoxColumn();
cbc.ThreeState = true;
this.dataGridView1.Columns.Add(cbc);

然后,您需要做的就是将以下事件处理程序添加到DataGridView,以便单击并双击CheckBox:

this.dataGridView1.CellContentClick += ThreeState_CheckBoxClick;
this.dataGridView1.CellContentDoubleClick += ThreeState_CheckBoxClick;

private void ThreeState_CheckBoxClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxColumn col = this.dataGridView1.Columns[e.ColumnIndex] as DataGridViewCheckBoxColumn;

    if (col != null && col.ThreeState)
    {
        CheckState state = (CheckState)this.dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue;

        if (state == CheckState.Unchecked)
        {
            this.dataGridView1[e.ColumnIndex, e.RowIndex].Value = CheckState.Checked;
            this.dataGridView1.RefreshEdit();
            this.dataGridView1.NotifyCurrentCellDirty(true);
        } 
    }
}

基本上,默认情况下,切换顺序为:Checked => Indeterminate => Unchecked => Checked。因此,当click事件触发Uncheck值时,您将其设置为Checked并强制网格使用新值刷新。