I have a problem binding data to a custom column DataGridView. I created a column that shows the rating for star-images according to the int value that it receives from the database. When I test it by adding lines manually, it works fine. But when I bind data to it, value is always null.
Here is the class code RatingColumn:
class RatingColumn : DataGridViewImageColumn
{
public RatingColumn()
{
this.CellTemplate = new RatingCell();
this.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.ValueType = typeof(int);
this.Name = "Rating";
this.ImageLayout = DataGridViewImageCellLayout.Stretch;
}
}
public class RatingCell : DataGridViewImageCell
{
static Image[] starImages;
static RatingCell()
{
starImages = new Image[11];
for (int i = 0; i < 11; i++)
starImages[i] = (Image)Properties.Resources.ResourceManager.
GetObject("rating_" + i.ToString());
}
public RatingCell()
{
this.ValueType = typeof(int);
}
protected override object GetFormattedValue
(object value, int rowIndex, ref DataGridViewCellStyle cellStyle,
TypeConverter valueTypeConverter,
TypeConverter formattedValueTypeConverter,
DataGridViewDataErrorContexts context)
{
return value == null ? starImages[0] : starImages[(int)value];
}
protected override void Paint
(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds,
int rowIndex, DataGridViewElementStates elementState, object value,
object formattedValue, string errorText, DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
Image cellImage = (Image)formattedValue;
base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState,
value, cellImage, errorText, cellStyle, advancedBorderStyle,
(paintParts & ~DataGridViewPaintParts.SelectionBackground));
}
}
I bind data using DataProperyName
RatingColumn col = new RatingColumn();
col.DataPropertyName = "Rating";
When I bind the same data with a DataGridViewTextBoxColumn, it works fine.