简体   繁体   中英

datagrid column value not displaying c# winform

I have a business object that returns a list of objects. This list is then being used as a datasource for a datagridview on a winform. I load my list, set it to the datasource, refresh and view. One of the columns is present but has no values. I see the header but no data. The column is for TruckColorId. Id shows the correct value. Debugging the code I can see that there are objects in the list with all the properties I expect to see correctly with data, including the field in question.

If I select a row and do a foreach loop of the selected row all columns have value but the 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"
            },
        };
    }
  }

And here is the code in my form to load the trucks:

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

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

try this

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM