C# 以编程方式选中刚刚取消选中的DataGridView复选框

C# 以编程方式选中刚刚取消选中的DataGridView复选框,c#,winforms,datagridview,C#,Winforms,Datagridview,我知道以前也有人问过类似的问题,但没有一个解决方案对我有帮助 我在未绑定的DataGridView中有一个DataGridViewCheckBoxColumn。 在CellContentClick事件中,当复选框未选中时,我会提示用户是否要根据DataGridView背后的业务规则继续此操作,如果他们选择不继续,我会重新选中复选框 正是这种对复选框的重新检查不起作用 这是我的密码: private void dgvPeriods_CellContentClick(object sender, D

我知道以前也有人问过类似的问题,但没有一个解决方案对我有帮助

我在未绑定的DataGridView中有一个DataGridViewCheckBoxColumn。
CellContentClick
事件中,当复选框未选中时,我会提示用户是否要根据DataGridView背后的业务规则继续此操作,如果他们选择不继续,我会重新选中复选框

正是这种对复选框的重新检查不起作用

这是我的密码:

private void dgvPeriods_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == dgvPeriods.Columns["colSelected"].Index)
    {
        dgvPeriods.CommitEdit(DataGridViewDataErrorContexts.Commit);
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dgvPeriods[e.ColumnIndex, e.RowIndex];

        if (chk.Value = chk.FalseValue)
        {
            If (MessageBox.Show("Continue with this Operation?", "Continue",  MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                chk.Value = chk.TrueValue;
                return;
            }
        }
    }
}
正在设置单元格的值,但在视觉上未选中复选框

如果我尝试了不同类型的
TrueValue
FalseValue
(布尔值与字符串),我尝试了调用
Refresh()
,我尝试了调用
committedit()
,我尝试了使用
CheckState.Checked


我该怎么做才能直观地重新选中复选框?

您可以使用(正确的)方法在引发事件后立即提交编辑,因此1事件也会立即引发,而不是在当前单元格失去焦点后

在此计算新值:由于该值已更改,因此当前值与上一个值相反,假设这是一个
bool

此时,如果用户确认所做的选择,则重置该值并调用以在其当前状态下重新绘制复选框

注意:DataGridView的行为可能取决于操作的上下文


1-请注意,在上一个事件处理程序中的代码完成之前,实际上会立即引发此事件。

接受答案的另一个选项是。
private void dgvPeriods_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex != dgvPeriods.Columns["colSelected"].Index) return;

    bool newValue = (bool)dgvPeriods[e.ColumnIndex, e.RowIndex].Value;

    if (!newValue) {
        if (MessageBox.Show("Continue with this Operation?", "Continue", 
            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) {
            dgvPeriods[e.ColumnIndex, e.RowIndex].Value = true;
            dgvPeriods.RefreshEdit();
        }
    }
}

private void dgvPeriods_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    // You need to evaluate whether EndEdit() applies to just this Column 
    if (e.ColumnIndex != dgvPeriods.Columns["colSelected"].Index) return;
    dgvPeriods.EndEdit();
}