如何只绘制数据网格视图的单元格背景而不是其内容

本文关键字:背景 单元格 绘制 数据 数据网 视图 网格 | 更新日期: 2023-09-27 17:57:02

我只需要绘制 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;
                        }
                    }
                }
            }

如何只绘制数据网格视图的单元格背景而不是其内容


我不确定为什么您需要捕获 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;
                        }
                    }
                }
            }

应该是

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点将被下一个单元格擦除。