[英]Changing DataGridViewCheckBoxCell backcolor in CellPainting
I am trying to override the default DataGridViewCheckBoxCell
with a colored rectangle.我试图用彩色矩形覆盖默认的DataGridViewCheckBoxCell
。
I found the following post but it doesn't behave as expected: Drawing a filled circle or rectangle inside a DataGridViewCell in C# Winforms我发现了以下帖子,但它的行为不符合预期: 在 C# Winforms 中的 DataGridViewCell 内绘制实心圆或矩形
Here is my code:这是我的代码:
private void OrdersComponentsDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex > 0)
{
const float size = 20;
var datagridview = (sender as DataGridView);
var cell = datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell.Value != DBNull.Value && (bool)cell.Value)
{
// center of the cell
var x = e.CellBounds.X + e.CellBounds.Width / 2 - size/2;
var y = e.CellBounds.Y + e.CellBounds.Height / 2 - size/2;
RectangleF rectangle = new RectangleF(x, y, size, size);
e.Graphics.FillRectangle(Brushes.Yellow, rectangle);
e.PaintContent(e.CellBounds);
e.Handled = true;
}
}
}
After loading for the first time, all checked cells have a Gray backcolor.第一次加载后,所有选中的单元格都有灰色背景。 It disappear after scrolling the datagridview down and up back.它在向下和向上滚动 datagridview 后消失。
In addition, I set the DataGridView SelectionMode to FullRowSelect:另外,我将 DataGridView SelectionMode 设置为 FullRowSelect:
OrdersComponentsDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
But after I implement CellPainting
as described above, the blue selection backcolor is gone (see in the image) where the checkbox is checked.但是在我如上所述实现CellPainting
之后,蓝色选择背景色消失了(见图像),其中复选框被选中。
you can use base background painting method before drawing your own rectangle (just like documentation for DataGridView.CellPainting Event suggests)您可以在绘制自己的矩形之前使用基础背景绘制方法(就像DataGridView.CellPainting 事件的文档建议的那样)
if (cell.Value is bool && (bool)cell.Value)
{
e.PaintBackground(e.ClipBounds, cell.Selected);
// center of the cell
var x = e.CellBounds.X + e.CellBounds.Width / 2 - size / 2;
var y = e.CellBounds.Y + e.CellBounds.Height / 2 - size / 2;
RectangleF rectangle = new RectangleF(x, y, size, size);
e.Graphics.FillRectangle(Brushes.Yellow, rectangle);
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.