DataGridViewCheckBoxCell如何在表单加载期间设置时显示检查

我有一个DataGridView,它从DataTable加载数据,以及DataGridViewCheckBoxCells的未绑定列。 将DataGridView中的行与单独的DataTable与用户已保存的值进行比较,如果匹配,则应检查该行的复选框。

以下是比较值并将复选框值设置为“true”的代码:

foreach (int j in selectedObjectives) { foreach (DataGridViewRow r in dgvObjectives.Rows) { if (j == Convert.ToInt32(r.Cells["ObjectiveID"].Value)) { dgvObjectives.CurrentCell = r.Cells["Select"]; ((DataGridViewCheckBoxCell)r.Cells["Select"]).Value = true; //dgvObjectives.InvalidateCell(r.Cells["Select"]); //dgvObjectives.EndEdit(); //dgvObjectives.CommitEdit(DataGridViewDataErrorContexts.Commit); } if (Convert.ToInt32(r.Cells["ObjectiveID"].Value) == selectedIndex) { r.Selected = true; } } } 

当我在窗体加载private void WQMDrill_Load(object sender, EventArgs e)期间调用方法执行此操作时,值设置正确,但复选框不检查。 但是,在表单完成加载后调用时,代码可以正常工作。 不幸的是,我绝对需要在加载过程中检查这些。

我希望我对我的问题很清楚,对此事的任何帮助都将不胜感激。 如您所见,我试图单独使单元格无效,以及整个DataGridView控件。 我也有

 private void dgvObjectives_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (this.dgvObjectives.CurrentCell.ColumnIndex == 0) { this.dgvObjectives.CommitEdit(DataGridViewDataErrorContexts.Commit); } } 

在这段时间内不会发射。 谢谢。

您可以将复选框选择和更新逻辑放在DataBindingComplete事件处理程序中,这将在FormLoad之后但在向用户显示任何内容之前触发。

我不确定调用CommitEdit实际上会在单元格上触发Paint 。 如果列是复选框列,请尝试处理CellMouseUp事件并触发EndEdit

 private void dgvObjectives_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) { if (dgvObjectives.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn) { dgvObjectives.EndEdit(); } } 

我有同样的问题,并尝试了很多不同的方法来处理它,大多数失败,除非我尝试this.BeginInvoke(new CDelegate())