我试图用彩色矩形覆盖默认的DataGridViewCheckBoxCell
。
我找到了以下帖子,但它没有按预期运行: Drawing a filled circle or rectangle inside a DataGridViewCell in C# Winforms
这是我的代码:
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;
}
}
}
首次加载后,所有选中的单元格都有灰色背景色。向下和向上滚动数据网格视图后它会消失。
此外,我将DataGridView SelectionMode设置为FullRowSelect:
OrdersComponentsDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
但是在我按照上面的描述实现CellPainting
后,蓝色选择背景颜色消失了(见图中所示),其中选中了复选框。
答案 0 :(得分:1)
您可以在绘制自己的矩形之前使用基本背景绘制方法(就像DataGridView.CellPainting Event建议的文档一样)
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;
}