DataGridView中代码设置的复选框未正确显示选中状态
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 callyourBindingSource.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

