datagrid列值不显示c#winform

时间:2017-08-08 15:45:32

标签: c# winforms datagridview

我有一个返回对象列表的业务对象。然后,此列表将用作winform上datagridview的数据源。我加载我的列表,将其设置为数据源,刷新和查看。其中一列存在但没有值。我看到标题但没有数据。该列适用于TruckColorId。 Id显示正确的值。调试代码我可以看到列表中有对象具有我期望正确查看数据的所有属性,包括相关字段。

如果我选择一行并执行所选行的foreach循环,则所有列都具有值,但是TruckColorId。

public class TruckColor : EditBase 
{
   public int TruckColorId { get; set; }
   public override int Id
   {
    get { return TruckColorId; }
    set { TruckColorId = value; }
   }
}

public class EditBase
{
    public virtual int Id { get; set; }
    public string ShortCode { get; set; }        
    public string Description { get; set; }

    public IList<EditBase> GetAll()
    {
        return new List<EditBase>()
        {
            new TruckColor
            {
                Description = "abc",
                Id = 1,
                ShortCode = "A"
            },
            new TruckColor
            {
                Description = "abcd",
                Id = 2,
                ShortCode = "B"
            },
            new TruckColor
            {
                Description = "abcde",
                Id = 3,
                ShortCode = "C"
            },
        };
    }
  }

以下是我的表格中加载卡车的代码:

public void InitTrucks()
{
    TruckColor truck = new TruckColor();

    var trucks = truck.GetAll();
    if (trucks.Count() > 0)
    {
        dataGridView1.AutoGenerateColumns = true;                
        dataGridView1.DataSource = trucks;
        dataGridView1.Refresh();
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个

var trucks = truck.GetAll();
 if (trucks.Count() > 0)
{
    List<TruckColor> RealTrucks = trucks.Select(x=>(TruckColor)x).ToList();
    dataGridView1.AutoGenerateColumns = true;                
    dataGridView1.DataSource = RealTrucks;
    dataGridView1.Refresh();
}