如何让DataGridView的CellPainting事件与部分显示的单元格一起使用?

时间:2014-12-07 16:56:41

标签: c# datagridview custom-painting

我在C#winforms 4.0中有一个datagridview。我正在为背景颜色和边框做一些自定义单元格绘画。这是我在CellPainting事件中的代码:

 //Background color
 if (e.RowIndex / 3 % 2 == 0 && e.RowIndex > -1)
     e.CellStyle.BackColor = Color.LightGray;

 //Bottom border
 if (e.RowIndex % 3 == 2)
 {
    using (Pen p = new Pen(Brushes.Black))
    {
       p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
       e.Graphics.DrawLine(p, new Point(0, e.CellBounds.Bottom - 1), 
                              new Point(e.CellBounds.Right, e.CellBounds.Bottom - 1) );
    }
    e.PaintContent(e.CellBounds);
 }

这就是我的datagridview的样子(我无法发布图片,所以这里有一个链接) http://i.imgur.com/hLR3JjV.png

正如您所看到的那样,背景颜色在我的所有单元格中都有效,但边框不会为仅部分显示在datagridview中的单元格绘制。例如,我的图像是Column4中每一行的单元格

有人可以帮我弄清楚我能做些什么来让部分显示的细胞画出底部边框?

1 个答案:

答案 0 :(得分:2)

它被普通的细胞绘画代码再次透支。您必须使用e.Handled = true;来防止这种情况发生。这需要你做更多的工作,你还需要绘制背景。顺便说一下,永远不要改变paint事件处理程序中的属性。并且从左到右绘制,而不是0。  (e.PaintBackground(e.CellBounds, true);之前的usinge.Handled = true;之后的drawContent非常值得在将来找到。

我希望这能解决你的问题!祝你有愉快的一天!