c# - 如何只绘制 DataGridView 单元格背景而不是其内容?

标签 c# datagridview

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

关于c# - 如何只绘制 DataGridView 单元格背景而不是其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041044/

相关文章:

c# - 如何在 aspx 内容占位符内的 html 表单元素上设置特定 id

c# - datagridview 不允许用户删除行

c# - DataGridViewColumnHeader 加粗

c# - 刷新数据 GridView 不起作用

c# - 导出datagridview到word文档c#

c# - 如何将字符串反序列化为对象(格式类似于对象表示法的字符串)

c# - 一个对象可以比另一个对象长寿……这是什么意思?

c# - 使用 json.net 将 json 反序列化为 .net 对象

c# - SqlDependency - 如何解释 SqlNotificationEventArgs 属性?

c# - 带有 DataTableSource 的 DataGridView ComboBox 列