Hi @genush ,
When you use the CellPainting
event to set a background color in a DataGridView
, the color change is temporary unless you take specific steps to make it persistent. The DataGridView
automatically repaints cells, which can reset the background to the default color after the event handler finishes.
In order to customize the CellPainting
event to handle both drawing and background color you’ll need to override the default cell painting behavior by setting e.Handled = true
, which prevents the DataGridView
from repainting the cell afterward:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
using (Brush backColorBrush = new SolidBrush(Color.Yellow))
{
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
}
e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Background);
e.Handled = true; // This prevents the default paint from overriding your changes
}
}
With either approach, the color should persist, and e.Handled = true
will ensure your custom drawing stays in place. If you need conditional coloring, set the Style.BackColor
based on cell values before or after the CellPainting
event triggers.
Best Regards.
Jiachen Li
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.