cell painting in c# datagridview

genush 21 Reputation points
2024-10-29T14:43:29.41+00:00

I am trying to set the background color of cells in a c# datagridview by adding a handler for the cellpainting event. I call Graphics.FillRectangle on the cell bounds. The handler sets the background color correctly, however when the handler exits, the background color reverts to the default. Is there some way to make the background color persist after exiting the handler?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,027 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 32,376 Reputation points Microsoft Vendor
    2024-10-30T02:29:19.03+00:00

    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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.