DataGridViewCheckBoxCell 是否可以以编程方式接受 CheckState.Indesure,但不能

本文关键字:Indesure CheckState 但不能 方式接 是否 编程 DataGridViewCheckBoxCell | 更新日期: 2023-09-27 17:57:15

我有以下DataGridViewCheckBoxCell这是我DataGridView的一部分:

DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell(true) {Value = CheckState.Unchecked};
grdRow.Cells.Add(cell);
grdRow.Tag = key;
grdFilter.Rows.Add(grdRow);

稍后,我根据是否选中其他复选框来更新其状态。

var numChecked = cells.Count(c => c.Value.Equals(true));
cbCell.Value = (numChecked == cells.Count) ? CheckState.Checked : (numChecked == 0 ? CheckState.Unchecked : CheckState.Indeterminate);

这很好用。 但是,如果用户单击该复选框,它将在选中、未选中和不确定之间循环。 我只想在选中和未选中之间循环。

如果我将TriState设置为单元格上的False,则不再允许我将Value设置为CheckState.Indeterminate

有没有办法得到我想要的行为?

更新:

我尝试像这样捕获CellValueChanged事件:

void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    var changedCell = grdFilter.Rows[e.RowIndex].Cells[e.ColumnIndex];
    if(changedCell.Value.Equals(CheckState.Indeterminate))
        changedCell.Value = CheckState.Unchecked;
}

但是,这没有任何效果。 我仍然可以单击所有三个状态。 我已经验证了该事件在调试器下确实触发,并且 Value 属性确实设置为CheckState.Unchecked

DataGridViewCheckBoxCell 是否可以以编程方式接受 CheckState.Indesure,但不能

我认为

CellValueChanged 事件触发得太晚了,您无法抓住用户更改复选框列的值。 尝试连接 CurrentCellDirtyStateChanged 事件并提交更改:

void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e) {
    dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

然后在 CellValueChanged 事件中,只需更改 ThreeState 属性:

private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  ((DataGridViewCheckBoxCell)dgv.Rows[e.RowIndex].Cells[e.ColumnIndex]).ThreeState = false;
}

您可能应该过滤列以仅在复选框列等上执行此操作。