c# - 仅更改 DataGridView 中单元格一部分的背景颜色
问题描述
我正在使用 .NET Framework 4.6 创建一个 UserControl。
我希望我的 DataGridView 中单元格的背景颜色部分是一种颜色,部分是另一种颜色(即单元格包含一条曲线;在曲线的右侧,它是黑色的。在左侧,它是白色的)。通常,我会使用以下内容来更改单元格的背景颜色:
dataGridView1.Rows[row].Cells[column].Style.BackColor = Color.Red;
我考虑的一个想法是向 DataGridViewCell 添加一个 GraphicsPath 对象,但我已经查看了这些方法,但没有找到这样做的方法。
如果您对如何进行此操作有任何想法,请告诉我。
如果我找不到这样做的方法,我可能只会创建一个 GraphicsPath 对象数组。也欢迎替代品。
解决方案
通过课堂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;
}
推荐阅读
- java - 如何在接口中使用枚举作为函数声明的参数?
- mongodb - mongo db如何存储像图这样的多关系
- python - 无法遍历嵌套列表
- windows - 使用纱线客户端运行 spark-shell 时出现问题,错误客户端。传输客户端:无法发送 RPC
- python - 如何从 python datetime 中的当前时间获取 unix 时间戳 x 秒?
- android - 每次应用启动时主要活动都会打开
- php - 我需要一种更有效的方式将我的多选复选框表单提交到我的数据库
- javascript - 根据对象在数组中添加元素
- bootstrap-4 - 如何更改轮播图标 boostrap 4 的颜色
- mysql - vb.net mysql 用日期插入命令