首页 > 解决方案 > 为什么此 DataGridView ComboBox 单元格中的 EditedFormattedValue 和实际显示的值没有更新?

问题描述

我有一个带有一列组合框的 DataGridView。这些组合框可以容纳 1-24 之间的数字。我在 DGV 中有 8 行,我想防止任何两行在组合框中选择相同的数字。如果更改的 CB 与任何其他 CB 冲突,我将更改回存储在“CorrectSlotSelections”中的先前值设置回。如果更改有效且没有冲突,我将更新存储在“CorrectSlotSelections”中的值。

这一切都正常工作,但是如果发现屏幕上显示的值无效,即使我覆盖了不正确的值,它也不会更新。在调试模式下检查 DGV 后,我可以看到我已经完全覆盖了该值,但属性“EditedFormattedValue”仍然显示旧的、不正确的值。如何更改它以更新 UI 以显示更正的值?

// This event handler manually raises the CellValueChanged event 
// by calling the CommitEdit method. 
void dataGridView1_CurrentCellDirtyStateChanged(object sender,
    EventArgs e)
{
    if (this.ChannelConfigDataGridView.IsCurrentCellDirty)
    {
        // This fires the cell value changed handler below
        ChannelConfigDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

private void ChannelConfigDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)ChannelConfigDataGridView.Rows[e.RowIndex].Cells[2];
    if (cb.Value != null)
    {
        // Check all rows for a cell in column 3 that has the value that was just changed.
        List<DataGridViewRow> rowsWithDuplicateValue = ChannelConfigDataGridView.Rows.Cast<DataGridViewRow>().Where(x => (int)x.Cells[2].Value == (int)cb.Value).ToList();
        if (rowsWithDuplicateValue == null || rowsWithDuplicateValue.Count() == 0)
        {
            return;
        }

        // If more than one item with this value was found we must handle the duplicates.
        if (rowsWithDuplicateValue.Count() > 1)
        {
            ChannelConfigDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = CorrectSlotSelections[e.RowIndex];
        }
        // If only one was found update the correct slot selections.
        else if(rowsWithDuplicateValue.Count() == 1)
        {
            CorrectSlotSelections[e.RowIndex] = (int)cb.Value;
        }
        ChannelConfigDataGridView.Invalidate();
    }
}

标签: c#datagridview

解决方案


推荐阅读