【问题标题】:How can I make a DataGridView refresh the entire row when a CheckBoxCell is clicked?单击 CheckBoxCell 时,如何使 DataGridView 刷新整行?
【发布时间】:2023-04-01 04:16:02
【问题描述】:

我有一个 DataGridView,它数据绑定到我自己的一个类的对象列表。 DataGridView 设置为显示一个文本列和两个复选框列,其行为类似于单选按钮:单击未选中的一个将选中它并取消选中另一个,而单击选中的则什么都不做。

我使用类似以下的类来执行此操作:

public class YesNoQuestion
{
    public string Text { get; set; }
    public bool Value { get; set; }

    public bool Yes
    {
        get { return Value; }
        set
        {
            // This is supposed to work like a radio button, can't be unset.
            if (value)
            {
                Value = true;
            }
        }
    }

    public bool No
    {
        get { return !Value; }
        set
        {
            // This is supposed to work like a radio button, can't be unset.
            if (value)
            {
                Value = false;
            }
        }
    }
}

在幕后,这按预期工作:将“Yes”设置为 true 将“Value”设置为 true,将“No”设置为 false,反之亦然,但您不能将“Yes”或“No”设置为假的。

问题在于 DataGridView 行在该行未聚焦之前不会更新,这意味着(例如)取消选中“是”在基础属性仍然为“真”并且选中“否”时不会取消选中“是”,而基础属性已更改为 false。

如果我离开该行,则数据显示正确。我想做的是确保无论何时单击任一复选框,都会立即重新加载整行的数据。

如何做到这一点?

在对有关更新 当前 单元格值的问题提出建议后,我尝试添加以下内容:

private void dgvQuestions_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgvCheckValues.IsCurrentCellDirty)
    {
        dgvCheckValues.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

这适用于当前单元格的值,因此您无法取消选中某个框,但其他单元格仍处于选中状态。我尝试添加dgvCheckValues.InvalidateRow(dgvCheckValues.CurrentRow.Index);,但没有效果。

【问题讨论】:

    标签: .net winforms datagridview refresh


    【解决方案1】:

    最后我想通了。这是因为我使用的是List 而不是BindingList

    或者,使用BindingSource 作为 DGV 的数据源并将List 设置为BindingSource 的源。

    【讨论】:

    • 我认为这个问题值得保留,即使我已经找到了答案,但我会留给版主来决定是否应该删除它。
    猜你喜欢
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多