You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGridView中代码设置的复选框未正确显示选中状态

Fix for DataGridViewCheckBoxColumn Refresh Issue After Context Menu Operations

I’ve run into this exact scenario before—here’s what’s going on and how to fix it:

Root Cause

When you left-click a DataGridViewCheckBoxCell (even without toggling its state), the cell enters edit mode. The visible checkbox you see is actually a hosted CheckBox control, not the cell’s underlying value display. When you run your bulk operation via the context menu, you’re updating the cell’s Value property, but the edit-mode checkbox doesn’t sync with this change automatically. Switching rows forces the cell to exit edit mode, which is why the state finally updates then.

Solution

You need to explicitly end the cell’s edit state before modifying values, then trigger a UI refresh to make the changes visible immediately.

Here’s how to adjust your reverse-selection code:

private void ReverseSelectionToolStripMenuItem_Click(object sender, EventArgs e)
{
    // First, force the DataGridView to exit edit mode completely
    dgv.EndEdit(DataGridViewDataErrorContexts.Commit);
    
    // Your existing reverse selection logic (add check for new row to avoid errors)
    DataGridViewColumn gridcol = dgv.Columns["YourCheckBoxColumnName"]; // Replace with your actual column name/index
    foreach (DataGridViewRow dr in dgv.Rows)
    {
        if (!dr.IsNewRow) // Skip the empty new row placeholder if enabled
        {
            bool currentValue = Convert.ToBoolean(dr.Cells[gridcol.Index].Value);
            dr.Cells[gridcol.Index].Value = !currentValue;
        }
    }
    
    // Force the DataGridView to refresh the UI to reflect changes
    dgv.Refresh();
}

Why Your Previous Attempts Didn’t Work

Calling ClearSelection() or switching selected rows doesn’t address the underlying edit mode issue. The cell is still locked in edit state, so the hosted CheckBox control doesn’t read the updated Value property until it exits edit mode.

Extra Tips

  • If you’re working with a data-bound DataGridView, you might also need to call yourBindingSource.ResetBindings(false) after updating values to ensure the data source syncs with the UI.
  • For other bulk operations (select all/deselect all), apply the same pattern: end edit first, modify values, then refresh.

内容的提问来源于stack exchange,提问作者Infrisios

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 17:59:05