自定义datagridview列上的数据绑定出现问题
本文关键字:问题 数据绑定 datagridview 自定义 | 更新日期: 2023-09-27 17:57:50
我在将数据绑定到自定义DataGridView
列时遇到问题。我创建了一个列,根据它从数据库中获得的int值,显示按星图像的评级
当我通过手动添加行来测试它时,它可以完美地工作。但当我将数据绑定到它时,值总是null
。
这是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)
{
//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));
}
}
我使用DataProperyName 绑定数据
RatingColumn col = new RatingColumn();
col.DataPropertyName = "Rating";
当我将相同的数据绑定到DataGridViewTextBoxColumn时,它可以正常工作。
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];
}