How can I get the CellPainting event of my DataGridView to work with partially displayed cells?

3k views Asked by At

I have a datagridview in C# winforms 4.0. I am doing some custom cell painting to the background color and for the borders. Here is my code from the CellPainting event:

 //Background color
 if (e.RowIndex / 3 % 2 == 0 && e.RowIndex > -1)
     e.CellStyle.BackColor = Color.LightGray;

 //Bottom border
 if (e.RowIndex % 3 == 2)
 {
    using (Pen p = new Pen(Brushes.Black))
    {
       p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
       e.Graphics.DrawLine(p, new Point(0, e.CellBounds.Bottom - 1), 
                              new Point(e.CellBounds.Right, e.CellBounds.Bottom - 1) );
    }
    e.PaintContent(e.CellBounds);
 }

And this is what my datagridview looks like(I can't post an image, so here is a link to it) https://i.stack.imgur.com/EuFnr.png

As you can see the background color is working across all my cells, but the border is not painting for cells that are only partially displayed in the datagridview. Eg from my image is the cell in every row in Column4

Can someone please help me figure out what I can do to get the partially displayed cells to paint the bottom border?

1

There are 1 answers

0
Xeidos On BEST ANSWER

It gets overdrawn again by the normal cell painting code. You must use e.Handled = true; to prevent that from happening. That requires you to do more work, you also need to draw the background. Btw, never change properties in a paint event handler. And draw from left to right, not 0. (e.PaintBackground(e.CellBounds, true); before the using and e.Handled = true; after the drawContent) it is well worth being found in the future.

I hope this will solve your problem! Have a nice day!