首页 > 解决方案 > 仅更改 DataGridView 中单元格一部分的背景颜色

问题描述

我正在使用 .NET Framework 4.6 创建一个 UserControl。

我希望我的 DataGridView 中单元格的背景颜色部分是一种颜色,部分是另一种颜色(即单元格包含一条曲线;在曲线的右侧,它是黑色的。在左侧,它是白色的)。通常,我会使用以下内容来更改单元格的背景颜色:

dataGridView1.Rows[row].Cells[column].Style.BackColor = Color.Red;

我考虑的一个想法是向 DataGridViewCell 添加一个 GraphicsPath 对象,但我已经查看了这些方法,但没有找到这样做的方法。

如果您对如何进行此操作有任何想法,请告诉我。

如果我找不到这样做的方法,我可能只会创建一个 GraphicsPath 对象数组。也欢迎替代品。

标签: c#.net

解决方案


通过课堂CellPainting事件,DataGridView您可以为单元格绘制任何类型的背景

例子

private void DataGridView1_CellPainting(object sender, 
    DataGridViewCellPaintingEventArgs e)
{
    var cellBounds = e.CellBounds;

    // Left part of cell
    cellBounds.Width = cellBounds.Width / 2;

    e.CellStyle.BackColor = Color.Black;
    e.CellStyle.ForeColor = Color.White;
    e.Graphics.SetClip(cellBounds);
    e.PaintBackground(e.ClipBounds, true);

    // draw all parts except background
    e.Paint(e.CellBounds, 
        DataGridViewPaintParts.All & (~DataGridViewPaintParts.Background));

    // Right part of cell
    cellBounds.X = cellBounds.Right;

    e.CellStyle.BackColor = Color.White;
    e.CellStyle.ForeColor = Color.Black;
    e.Graphics.SetClip(cellBounds);
    e.PaintBackground(e.ClipBounds, true);

    // draw all parts except background
    e.Paint(e.CellBounds, 
        DataGridViewPaintParts.All & (~DataGridViewPaintParts.Background));

    e.Handled = true;
}

推荐阅读