【问题标题】:Programmatically check a DataGridView CheckBox that was just unchecked以编程方式检查刚刚未选中的 DataGridView CheckBox
【发布时间】:2020-05-26 18:55:28
【问题描述】:

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

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

这是对 CheckBox 的重新检查不起作用。

这是我的代码:

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;
            }
        }
    }
}

正在设置单元格的值,但在视觉上未检查 CheckBox。

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

我可以做些什么来重新检查 CheckBox ?

【问题讨论】:

标签: c# winforms datagridview


【解决方案1】:

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

在此处评估新值:由于值已更改,因此当前值与以前的值相反,假设这是一个bool 列。

此时,如果用户确认所做的选择,则重置该值并调用RefreshEdit() 以在当前状态下重新绘制 CheckBox。

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

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();
}

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

【讨论】:

    【解决方案2】:

    你应该在检查后使用YourDataGridview.EndEdit()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 2017-02-21
      相关资源
      最近更新 更多