Search code examples
c#winformsdatagridviewdatagridviewcheckboxcell

How can the datagridview directly after assign a value in code?


I have a WinForms application and i use datagridview in form. The DataGridView have many checkbox columns and the cells can be selected and processed by code.

So it's possible to check/uncheck all cells or copy to/insert from clipboard. This works fine except the last selected checkbox. 1st value is not shown as long as the cell is selected.

I have tried to set SuspendLayout, Refresh, Update and then ResumeLayout. But any one of them does not work for me.

private void SetCheckBoxCells(bool value)
{
  myDataGridView.SuspendLayout();

  foreach (var cell in myDataGridView.SelectedCells)
  {
    (cell as DataGridViewCheckBoxCell).Value = value;
  }

  myDataGridView.Refresh();
  myDataGridView.Update();         
  myDataGridView.ResumeLayout();
}

I expect that all cells are visually set/unset after click on the menu entry, but the last one is visually set after deselect the cells.


Solution

  • The issue is almost certainly not caused by the Refresh/Update. If that was a problem, you'd see a correct value after first manual edit in other cell. You can also check the value, i.e. simply:

    MSgbox(myDataGridView.Rows[1].Cells[0].Value.ToString);
    

    Obviously, with correct indexes. I'm sure you'll get what you see, though.

    foreach in SelectedCells should be pretty robust and does not suffer from index error, so I would double check, whether a CellEdit state, or CurrentCell focus or some event does not interfere with the first cell, preventing it to be updated.

    Perhaps try setting current cell to something outside the selected range:

    myDataGridView.CurrentCell = myDataGridView.Rows[1].Cells[0];
        // some other cell not included in selection
    

    What the integers (x1 to y2) are doing there? They're not employed. Just left from testing? Try to address the troublesome cell directly (just for debugging), simply like that:

    myDataGridView.Rows[1].Cells[0].value = True
    

    Obviously with correct indexes. Perhaps it will tell a bit more about the problem.