DataGridCellCollection Style BackColor didn't change after the BackColor set

23 Views Asked by At

There is a problem. It will show a colordialog form when I click a cell. After I set a new color, the current cell back color didn't refresh. But when I click another cell or the current cell, the cell back color changes.

There is my code in C#:

private void DGV_CellClick(object sender, DataGridViewCellEventArg e)
{
DataGridView dgv = sender as DataGridView;
int rowIndex = e.RowIndex, colIndex = e.ColumnIndex;
if (colIndex==1)
{
ColorDialog dialog = new ColorDialog();
if (dialog.ShowDialog()==DialogResult.OK)
{
dgv.Rows[rowIndex].Cells[colIndex].Style.BackColor=dialog.Color;
}
}
}

I tried dgv.Refresh() and dgv.Update(). But it still didn't change.

Is it any method to solve my issue?

I want to change the current cell back color after setting a new color from ColorDialog.

1

There are 1 best solutions below

0
user9252202 On

Try using this code
{ dgv.Rows[rowIndex].Cells[colIndex].Style.BackColor = dialog.Color;

        // This will refresh the DGV cells
        dgv.InvalidateCell(colIndex, rowIndex);
    }

By calling dgv.InvalidateCell(colIndex, rowIndex), you are instructing the DataGridView to repaint the cell, which will now reflect the updated background color.