DataGridViewCheckBoxCell how to show checked when set during form load

跟風遠走 提交于 2019-11-30 09:20:56

问题


I have a DataGridView that loads data from a DataTable, along with an unbound column of DataGridViewCheckBoxCells. The rows in the DataGridView are compared with a separate DataTable with values the user has saved, and if there is a match, the checkbox for that row should check.

Here is the code that compares the values and sets the checkbox value to '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;
        }
    }
}

When I call the method to perform this action during the form load private void WQMDrill_Load(object sender, EventArgs e), the values are set correctly, but the checkboxes do not check. However, when called after the form is finished loading, the code works perfectly. Unfortunately for me, I absolutely need for these to check during the load process.

I hope I was clear with my issue, any help on this matter would be greatly appreciated. As you can see, I have tried to invalidate the cell alone, as well as the entire DataGridView control. I also have

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

That doesn't fire during this time. Thank you.


回答1:


You can put your checkbox selection and update logic in the DataBindingComplete eventhandler, this fires after the FormLoad but before anything is displayed to the user.




回答2:


I'm not certain that calling CommitEdit will actually fire the Paint on the cell. Try handling the CellMouseUp event and firing EndEdit if the column is a checkbox column.

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



回答3:


I had the same problem, and tried a lot of different ways to deal with it, most failed, except when I tried this.BeginInvoke(new CDelegate()).



来源:https://stackoverflow.com/questions/6537334/datagridviewcheckboxcell-how-to-show-checked-when-set-during-form-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!