4

我有一个从 DataTable 加载数据的 DataGridView,以及一个未绑定的 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);
    }
}

在此期间不会触发。谢谢你。

4

3 回答 3

1

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

于 2011-06-30T17:31:26.990 回答
0

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

private void dgvObjectives_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
    if (dgvObjectives.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn)
    {
        dgvObjectives.EndEdit();
    }
}
于 2011-06-30T15:56:48.313 回答
-1

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

于 2012-02-15T08:26:33.990 回答