Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind List of Classes into DataGridView

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?

like image 669
Yuriy Avatar asked Nov 10 '10 10:11

Yuriy


Video Answer


3 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 be updating the data in the datagridview ?

like image 86
Jla Avatar answered Oct 18 '22 23:10

Jla


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;}
   }
}
like image 45
Marc Gravell Avatar answered Oct 18 '22 21:10

Marc Gravell


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
like image 1
user890332 Avatar answered Oct 18 '22 23:10

user890332