Reputation: 1185
I have created a DataGridView, one of the cells (DataGridViewTextBoxCell) I would like to have a background image. To do this I have used the following on the CellPainting event.
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);
}
This works well and the image is on ever row in the position I want. However, the cell it is sitting in has a DataGridViewTextBoxCell with a numeric value. The image floats on top of this value and thus is hidden. I guess the ideal solution would be to make the DataGridViewTextBoxCell be "TopMost" but I couldn't figure out how to do this.
I then decided to try and make the background image partial transparent so the value underneath would be visual, so I changed my CellPainting code to below.
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);
}
This again worked and I could see the value with the background image surrounding it as I would like. However the next issue arise when I tried to update the value of the cell. Once I did that the previous value was visible and the new value that I was trying to set was overlapping it. I am now stuck.
Any advice/guidance would be very appreciated.
Upvotes: 1
Views: 6227
Reputation: 3388
You have to set e.Handled = true
to prevent the system from painting. The below code works as you expected.
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);
}
}
}
Upvotes: 2