【发布时间】:2011-05-28 21:52:24
【问题描述】:
我在将数据绑定到自定义 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 时,它工作正常。
【问题讨论】:
-
您是否尝试过调用基础构造函数?公共 RatingColumn() : base()
标签: c# winforms data-binding datagridview custom-controls