如何在 DataGridView 中强制“刷新”

Fil*_*ida 3 c# datagridview winforms

我是一个新手,正在做我的第一个 C# 项目(在 Haskell 和 C 方面的经验也很少),正在寻找有关如何在我的程序中实现一个小功能的指导。

我有一个 DataGridView 表(包含 3 列复选框以及其他内容)供用户填写。连续选中第二个复选框时,必须取消选中第一个选中的复选框。我已经可以做到这一点,但问题是,第一个选中的只有在我在表中选择其他内容后才会取消选中。

这是与 CellValueChanged 事件有关的代码(评论中的内容是我试图帮助我的)

if (e.ColumnIndex == 0 || e.ColumnIndex == 1 || tabela_NormasDataGridView.Rows.Count == 0)
{
    return;
}

var isChecked = (bool)tabela_NormasDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

if (isChecked)
{
    for (int i = 2; i < 5; i++)
    {
        //Console.WriteLine("og " + e.ColumnIndex);
        DataGridViewCell cell = tabela_NormasDataGridView.Rows[e.RowIndex].Cells[i];
        //Console.WriteLine("segunda " + cell.ColumnIndex);
        if (cell.ColumnIndex != e.ColumnIndex)
        {
            cell.Value = false;
            //this.Refresh();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*ech 5

Try committing the change to force the refresh:

void tabela_NormasDataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e) {
    tabela_NormasDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
Run Code Online (Sandbox Code Playgroud)

Make sure you wire the event up.

  • @FilipeAlmeida在表单的构造函数中,添加`tabela_NormasDataGridView.CurrentCellDirtyStateChanged += tabela_NormasDataGridView_CurrentCellDirtyStateChanged;`,然后复制上面的代码片段。 (2认同)