用填充图案填充 DataGridView 单元格

Posted

技术标签:

【中文标题】用填充图案填充 DataGridView 单元格【英文标题】:Fill DataGridView cell with Hatch Pattern 【发布时间】:2017-03-10 09:09:04 【问题描述】:

有没有办法用 HatchPattern i C# 填充 DataGridView 单元格?

我尝试使用 dataGridView1.Rows[n].Cells[m].Style,但这样我只能更改单元格的背景颜色。

【问题讨论】:

HatchPattern 是什么意思?不清楚你在问什么 使用由两种颜色和 HatchStyle 组成的 HatchBrush 对象填充单元格。它通常用于填充形状。 我不明白你为什么要这样做,但请参阅this question 您的问题解决了吗? 【参考方案1】:

你需要owner-draw单元格,即编码CellPainting事件..

using System.Drawing.Drawing2D;
..
private void dataGridView1_CellPainting(object sender, 
                                       DataGridViewCellPaintingEventArgs e)

    Rectangle cr = e.CellBounds;
    e.PaintBackground(cr, true);

    Color c1 = Color.FromArgb(64, Color.GreenYellow);
    Color c2 = Color.FromArgb(64, e.State == DataGridViewElementStates.Selected ? 
               Color.HotPink : Color.RosyBrown) ;

    if (e.RowIndex == 2 && (e.ColumnIndex >= 3))
        using (HatchBrush brush = new HatchBrush(HatchStyle.LargeConfetti, c1, c2))
        
            e.Graphics.FillRectangle(brush, cr );
        
    e.PaintContent(cr);

请注意,我将影线颜色设为半透明以提高内容的可读性。我还检查了其中一个是否用于选中的单元格..

【讨论】:

以上是关于用填充图案填充 DataGridView 单元格的主要内容,如果未能解决你的问题,请参考以下文章