带有背景图像的Datagridview单元格

本文关键字:Datagridview 单元格 图像 背景 | 更新日期: 2023-09-27 17:51:11

我已经创建了一个DataGridView,其中一个单元格(DataGridViewTextBoxCell)我想有一个背景图像。为了做到这一点,我在CellPainting事件上使用了以下代码:

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        var image = Resources.item_qty_white;
        e.PaintBackground(e.ClipBounds, false);
        e.Graphics.DrawImageUnscaled(image, 1410, e.CellBounds.Top);
    }

这个效果很好,图像在我想要的位置上的每一行。然而,它所在的单元格有一个带数值的DataGridViewTextBoxCell。图像漂浮在该值的上方,因此被隐藏。我想理想的解决方案是使DataGridViewTextBoxCell是"TopMost",但我不知道如何做到这一点。

然后我决定尝试使背景图像部分透明,所以下面的值将是可见的,所以我改变了我的CellPainting代码如下。

 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        var image = Resources.item_qty_white;
        e.PaintBackground(e.ClipBounds, false);
        image.MakeTransparent(Color.White);
        e.Graphics.DrawImageUnscaled(image, 1410, e.CellBounds.Top);
    }

再次工作,我可以看到它周围的背景图像的值,因为我想。然而,下一个问题出现时,我试图更新单元格的值。一旦我这样做了,以前的值是可见的,我试图设置的新值是重叠的。我现在卡住了。

任何建议/指导将非常感激。

带有背景图像的Datagridview单元格

您必须设置e.Handled = true以防止系统绘制。下面的代码按预期工作。

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex != -1 && e.ColumnIndex == columnIndex)
    {
        if ((e.PaintParts & DataGridViewPaintParts.Background) != DataGridViewPaintParts.None)
        {
            e.Graphics.DrawImage(Resources.Image1, e.CellBounds);                    
        }
        if (!e.Handled)
        {
            e.Handled = true;
            e.PaintContent(e.CellBounds);
        }            
    }
}