c# - DataGridViewCheckBoxCell 可以以编程方式接受 CheckState.Inminated,但不能通过单击吗?

标签 c# .net winforms datagridview

我有以下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.Inminated .

有办法获得我想要的行为吗?

更新:

我 try catch 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

最佳答案

我认为 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;
}

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

关于c# - DataGridViewCheckBoxCell 可以以编程方式接受 CheckState.Inminated,但不能通过单击吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30945048/

相关文章:

c# - SOAP 扩展实现

c# - 为什么C#没有为char定义加法运算?

c# - 跨 dll 边界访问匿名/动态类型的属性会产生 RuntimeBinderException

c# - 通过 .NET DbConnection 连接到 DB2

c# - 具有十进制值或类似值的枚举

vb.net - 我如何发送向下箭头键?

c# - WebAPI 上传错误。 MIME 多部分流的预期结束。 MIME 多部分消息不完整

c# - 如何使用 LINQ 使用条件按子字符串对文件名进行排序?

c# - Task.Run 中的 Thread.Sleep

c# - 使用可拖动和可调整大小的选择窗口创建自定义图片框