自定义datagridview列上的数据绑定问题

时间:2011-05-28 21:52:25

标签: c# winforms data-binding datagridview custom-controls

我在将数据绑定到自定义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时,它可以正常工作。

1 个答案:

答案 0 :(得分:1)

        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];
    }