I need to bind a List<MyClass> myList to a DataGridView. And get in the results table with two columns ID and Name.
Code snippets:
private List<MyClass> myList = new List<MyClass>(){...};
public void BindClass()
{
    dataGridView.DataSource = myList;
}
public MyClass
{
   public MyDataClass Data{ get; set; }
}
public MyDataClass
{
   public string ID { get; set; }
   public string Name { get; set; }
}
Is it possible?
How about binding to an anonymous type:
public void BindClass() 
{
    dataGridView1.DataSource = myList.Select(myClass => new {myClass.Data.ID, myClass.Data.Name}).ToList();
}
Will you be updating the data in the datagridview ?
To do that without changing the model is exceptionally tricky (but possible), requiring ICustomTypeDescriptor or TypeDescriptionProvider, and a custom PropertyDescriptor. To be honest: not worth it.
Just add pass-thru properties:
public MyClass
{
   public MyDataClass Data{get; set;}
   [DisplayName("ID")]
   public string DataID {
     get {return Data.ID;}
     set {Data.ID = value;}
   }
   [DisplayName("Name")]
   public string DataName {
     get {return Data.Name;}
     set {Data.Name = value;}
   }
}
                        It's easy with LINQ as you can see in This answer
Here's a simple implementation of something I needed to attach to datagridview.
     DataGridView1.DataSource =  _
(From i In ItemList Select i.ListID, i.FullName, i.PurchaseDesc, i.EditSequence).ToList
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With