【问题标题】:How to cancel a checkbox in a DataGridView from being checked如何取消选中 DataGridView 中的复选框
【发布时间】:2015-02-05 14:59:53
【问题描述】:

我有一个数据绑定的 datagridview。如果不满足某些条件,如何取消在 datagridview 中选中的复选框?

private void dataGridViewStu_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridViewStu.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

private void dataGridViewStu_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
}

【问题讨论】:

    标签: c# checkbox datagridview unchecked


    【解决方案1】:

    一种可能的方法是处理DataGridView 上的CurrentCellDirtyStateChanged 事件。检查您的条件并确保当前单元格是CheckBoxCell,如果两个条件都满足,则调用CancelEdit

    private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
      if (youShouldCancelCheck &&
          this.dataGridView1.IsCurrentCellDirty &&
          this.dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
      {
        this.dataGridView1.CancelEdit();
        // Addition code here.
      }
    }
    

    编辑

    我在if 语句中添加了一个附加条件,以在运行CancelEdit 和您的附加代码之前检查单元格是否脏。这不应再运行两次。发生的事情是:

    1. 用户单击复选框。 IsCurrentCellDirty = trueCurrentCellDirtyStateChanged 被解雇。
    2. 满足条件。 CancelEdit 被触发,这会取消所有更改并设置 IsCurrentCellDirty = false。因此CurrentCellDirtyStateChanged 再次被解雇。

    CurrentCellDirtyStateChanged 仍会被触发两次,但条件内的代码只会在脏时运行。

    【讨论】:

    • 我试过你的代码,它“工作”,但我需要在 CancelEdit 方法之后运行额外的代码,它似乎运行了两次额外的代码。它应该只运行一次。
    • @Jnr 你在哪里运行附加代码以便我可以重现错误?我明天去看看。
    • 让我在你的答案中编辑你的代码,这样你就可以明白我的意思了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多