Bind class list in DataGridView

I need to bind List<MyClass> myList to a DataGridView . And go to the result table with two column identifiers and a 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?

+7
c # data-binding winforms datagridview
source share
4 answers

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 update the data in a datagridview?

+17
source share

To do this, changing the model is extremely difficult (but possible), requiring an ICustomTypeDescriptor or TypeDescriptionProvider and a custom PropertyDescriptor . Honestly: 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;} } } 
+2
source share

Easy with LINQ, as you can see in This answer

Here is a simple implementation of what I needed to attach to a datagridview.

  DataGridView1.DataSource = _ (From i In ItemList Select i.ListID, i.FullName, i.PurchaseDesc, i.EditSequence).ToList 
+1
source share

No, you cannot do this out of the box. You will need to write your own binding source (most likely with special logic for your specific purpose) to allow you to β€œdrill” deeper than just one level of properties.

0
source share

All Articles