Reputation: 2691
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?
Upvotes: 7
Views: 27518
Reputation: 1361
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
Upvotes: 1
Reputation: 11374
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 ?
Upvotes: 20
Reputation: 1062780
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;}
}
}
Upvotes: 2
Reputation: 117240
No, you can't do this out of the box. You will have to write a custom binding source (most likely with specialized logic for your specific purpose) to allow 'drilling' deeper than just 1 level of properties.
Upvotes: 0