As described in the MSDN Docs, in the Remarks section of the DataGridViewImageColumn Class, to replace the default Error Image with a custom Image, requires a custom class derived from DataGridViewImageCell.
This allows to override the DefaultNewRowValue property, usually read-only, setting the custom Image.
Also, eventually, to override the PaintErrorIcon method.
This is an implementation of custom DataGridViewImageColumn
, coupled with a custom DataGridViewImageCell
, which can be configured to show a different default Image when no Image is specified or the bound field value is null.
If no image is specified, the cell will show an empty content, also in the DataGridView New Row.
The class constructor has several overloads. You can specify:
- The Column Name (defaults to
ImageColumn
).
- The Column's Header text (defaults to
ImageColumn
).
- The
DataPropertyName
, if the Column will be bound to a DataSource field (defaults to string.Empty
).
- The Image used as placeholder when no image is present (defaults to an empty Bitmap)
To add the custom Image column to a DataGridView, use the DataGridView.Columns.Add()
method, passing a new DGVCustomImageColumn
, initialized as needed.
Here, I'm just setting the Column.Name
, the HeaderText
and the DataPropertyName
:
dataGridView1.Columns.Add(new DGVCustomImageColumn("ImageCol", "Image", "ImageField"));
The DGVCustomImageColumn
class:
using System.Drawing;
using System.Windows.Forms;
class DGVCustomImageColumn : DataGridViewImageColumn
{
private Bitmap dgvErrorBitmap = new Bitmap(1, 1);
public DGVCustomImageColumn()
: this("ImageColumn", "ImageColumn", string.Empty, null) { }
public DGVCustomImageColumn(string colName, string headerText)
: this(colName, headerText, string.Empty, null) { }
public DGVCustomImageColumn(string colName, string headerText, string dataField)
: this(colName, headerText, dataField, null) { }
public DGVCustomImageColumn(string colName, string headerText, string dataField, Bitmap errorImage)
{
this.CellTemplate = new CustImageCell(errorImage ?? dgvErrorBitmap);
this.DataPropertyName = dataField;
this.HeaderText = headerText;
this.Image = errorImage ?? dgvErrorBitmap;
this.Name = colName;
}
protected class CustImageCell : DataGridViewImageCell
{
public CustImageCell() : this(null) { }
public CustImageCell(Bitmap defaultImage) => this.DefaultNewRowValue = defaultImage;
public override object DefaultNewRowValue { get; }
}
}