自定义DataGridView单元格绘画

时间:2014-04-24 17:31:44

标签: c# datagridview

我试图绘制自己的网格线,因为我想要比默认数据网格视图线更粗的线条。这是我用来执行此操作的代码:

 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));
        }
    }

绘制线条,但不会在最后一列绘制水平线条,并且不会在最后一行绘制垂直线条。这些线条创建的网格是一个列,行太小。有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

尝试设置e.Handled = true;来控制绘画。添加回单元格的默认绘图:

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;

您的代码也在左侧和顶部使用0,但CellBounds值基于控件的内部空间,因此您应该使用e.CellBounds.Lefte.CellBounds.Top

您可能需要调整线条的点数以考虑这些边框的厚度,此时它们会在细胞外流血。