Text overflows for custom cell painting of DataGridView

后端 未结 1 356
我在风中等你
我在风中等你 2021-01-14 04:15

Here is my cell painting method

DataGridView grid = (DataGridView)sender;

        if (e.RowIndex == -1 || e.ColumnIndex == -1) { return; }
        if ((grid         


        
相关标签:
1条回答
  • 2021-01-14 05:20

    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.ClipBoundsto 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:

    • You could also set the target rectangle for for both DrawText and DrawString, but drawing in different fonts will make that a bit harder.
    • For some reason the clipped region doesn't seem to work with 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..

    0 讨论(0)
提交回复
热议问题