GrandpaG
GrandpaG

Reputation: 11

Display header text after CellPainting event in winforms datagridview

I have a datagridview control where I want to put a 3px line at the bottom of each header cell to look something like

enter image description here

I have put code in CellPainting even for the datagridview like:

           if (e.RowIndex < 0)   // headers
            {

                Rectangle newRect = new Rectangle(e.CellBounds.X, e.CellBounds.Y - 1 + e.CellBounds.Height, e.CellBounds.Width, 2);
                using (Brush gridBrush = new SolidBrush(Color.Red))
                {
                    e.Graphics.FillRectangle(gridBrush, newRect);
                }e.Handled = true;
            }

The red line appears correctly (I will add the 3px later). However, the header text now is missing.

I am assuming that setting the e.Handled = true; tells to not continue to draw the original header text. If I set it to false, then the red line disappears. There is no base.CellPainting type concept for this control (apparently).

I know I can draw the text myself, but then I have to worry about alignment, font...

Is there now way to tell the system to do both the line AND draw original header text?

I am willing to try other approaches if necessary.

Upvotes: 0

Views: 324

Answers (1)

TaW
TaW

Reputation: 54433

There is no base.CellPainting type concept for this control

Indeed; the DGV has more options than just calling the base event.

Instead you can let it draw the parts separately and in the order you want:

if (e.RowIndex < 0)   // headers
{
    e.PaintBackground(e.CellBounds, true);   // draw the default background

    Rectangle newRect = 
              new Rectangle(e.CellBounds.X, e.CellBounds.Bottom - 2, e.CellBounds.Width, 2);
    e.Graphics.FillRectangle(Brushes.Red, newRect);  // now draw the red line

    e.PaintContent(e.CellBounds);        // finally draw the text in the default way

    e.Handled = true;                   // done
}

If you disable dgv.EnableHeadersVisualStyles you can also set many other properties to be used when drawing the column headers..

For even finer-tuned options you may want to look into MSDN.

Upvotes: 0

Related Questions