Here is my cell painting method
DataGridView grid = (DataGridView)sender;
if (e.RowIndex == -1 || e.ColumnIndex == -1) { return; }
if ((grid
The CellPainting
event will let you draw onto the whole visible area of the DataGridView
, including all headers and excluding only scrollbars.
It does provide you with the Cell
's area in the e.CellBounds
rectangle but it will still let you draw outside of it.
To restrict your drawing to the Cell
the simplest way is to change the e.Graphics.ClipBounds
to the cell's bounding rectangle; to make sure no overflow into the rowheaders can occur we restrict it to only start left of the rowheader, maybe like this:
int rhw = grid.RowHeadersWidth;
Rectangle clip = e.CellBounds;
if (e.CellBounds.X < rhw)
clip = new Rectangle(rhw, clip.Y, clip.Width - rhw, clip.Height);
e.Graphics.SetClip(clip, CombineMode.Replace);
Now nothing you draw can overflow.
Notes:
TextRenderer
.Also note: I couldn't reproduce the effect of underflowing into the headers. I can imagine that it might come from the cell's top can lying in the negative if the top cell isn't quite fully visible. (My DGV only let's me scroll by integral rows, though.) To exclude these cases you may need to calculate a better clipping rectangle that only starts right below the header cells..