Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

c# - Custom DataGridView Cell Painting

I'm trying to draw my own grid lines because I want thicker lines than the default data grid view lines. This is the code I'm using to do it:

 private void dgv_Wafer_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        using (Pen p = new Pen(Brushes.Black, 12))
        {
            e.Graphics.DrawLine(p, new Point(0, e.CellBounds.Bottom), new Point(e.CellBounds.Right, e.CellBounds.Bottom));
        }
        using (Pen p = new Pen(Brushes.Black, 6))
        {
            e.Graphics.DrawLine(p, new Point(e.CellBounds.Right, 0), new Point(e.CellBounds.Right - 1, e.CellBounds.Bottom));
        }
    }

The lines are drawn but the horizontal lines won't be drawn in the last column and the vertical lines won't be drawn in the last row. The lines are creating a grid that is a column and row too small. Does anyone know how to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try setting the e.Handled = true; to control the painting. Add back in the default painting of the cells:

e.PaintBackground(e.ClipBounds, true);
e.PaintContent(e.ClipBounds);
using (Pen p = new Pen(Brushes.Black, 12)) {
  e.Graphics.DrawLine(p, new Point(e.CellBounds.Left, e.CellBounds.Bottom),
                         new Point(e.CellBounds.Right, e.CellBounds.Bottom));
}
using (Pen p = new Pen(Brushes.Black, 6)) {
  e.Graphics.DrawLine(p, new Point(e.CellBounds.Right, e.CellBounds.Top),
                         new Point(e.CellBounds.Right, e.CellBounds.Bottom));
}
e.Handled = true;

Your code was also using 0 for left and top, but the CellBounds values are based on the control's interior space, so you should use e.CellBounds.Left and e.CellBounds.Top

You might want to adjust the points of your line to account for the thickness of those borders, they are bleeding outside of the cell at the moment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...