Reputation: 31
I have a problem with binding data to custom DataGridView
column. I created column that shows rating by stars-images accordingly to the int value it gets from database.
When i test it by adding rows manually it works perfectly. But when i bind data to it the value is always null
.
Here is the code of the RatingColumn
class:
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)
{
//Here the value is always null
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 to DataGridViewTextBoxColumn it works fine.
Upvotes: 3
Views: 1562
Reputation: 252
protected override object GetFormattedValue
(object value , int rowIndex , ref DataGridViewCellStyle cellStyle ,
TypeConverter valueTypeConverter ,
TypeConverter formattedValueTypeConverter ,
DataGridViewDataErrorContexts context) {
int v = 0;
if ( value == null || Convert.IsDBNull ( value ) )
return starImages[0];
v = Convert.ToInt32 ( value ) - 1;
v = v < 0 ? 0 : ( v >= 3 ? 2 : v );
return starImages[v];
}
Upvotes: 1