gpt4 book ai didi

c# - 自定义 datagridview 列上的数据绑定(bind)问题

转载 作者:行者123 更新时间:2023-11-30 18:04:25 24 4
gpt4 key购买 nike

我在将数据绑定(bind)到自定义 DataGridView 列时遇到问题。我创建了根据从数据库中获取的 int 值按星图显示评级的列。
当我通过手动添加行来测试它时,它工作得很好。但是当我将数据绑定(bind)到它时,该值始终为 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 绑定(bind)数据

RatingColumn col = new RatingColumn();
col.DataPropertyName = "Rating";

当我将相同的数据绑定(bind)到 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];
}

关于c# - 自定义 datagridview 列上的数据绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6164565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com