如何仅绘制DataGridView单元格的背景而不是其内容?

7

我需要绘制DataGridView单元格仅背景,而不是其内容。但是,当我进行绘画时,它也会绘制其内容。请帮我解决这个问题。

我的代码如下:

private void Daywisegrid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == 0 )

            {
                using (Brush gridBrush = new SolidBrush(this.Daywisegrid.GridColor))
                {
                    using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
                    {
                        using (Pen gridLinePen = new Pen(gridBrush))
                        {
                            // Clear cell 
                            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                            //Bottom line drawing
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom-1 , e.CellBounds.Right, e.CellBounds.Bottom-1);


                            e.Handled = true;
                        }
                    }
                }
            }
2个回答

11


我不确定为什么您需要捕获CellPainting事件来更改单元格背景颜色,只需像这样操作即可。

Daywisegrid.Rows[RowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

但如果你想在绘画中实现它,请尝试这个方法

private void Daywisegrid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == 0 )

            {
                using (Brush gridBrush = new SolidBrush(this.Daywisegrid.GridColor))
                {
                    using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
                    {
                        using (Pen gridLinePen = new Pen(gridBrush))
                        {
                            // Clear cell 
                            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                            //Bottom line drawing
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom-1 , e.CellBounds.Right, e.CellBounds.Bottom-1);

                              // here you force paint of content
                             e.PaintContent( e.ClipBounds  );
                            e.Handled = true;
                        }
                    }
                }
            }

0

应该是

e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom-1 , e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);

e.CellBounds.Right,e.CellBounds.Bottom-1点将被下一个单元格擦除。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接