Reputation: 1687
I have a List of "Person" object:
public class Person
{
public Int32 Id { get; set; }
public String Name { get; set; }
public Document oDocument { get; set; }
}
And also there is Document class.
public class Document
{
public String Type { get; set; }
public String Code { get; set; }
}
I need to populate a DataGridView with that list showing some just two columns:Name(Person) and DocumentCode (Document)
I used this code, but I dont get what I want.
dgvPersona.DataSource = list;
Upvotes: 1
Views: 161
Reputation: 10143
try this:
public class Person
{
public Int32 Id { get; set; }
public String Name { get; set; }
public Document oDocument { get; set; }
}
public class Document
{
public String Type { get; set; }
public String Code { get; set; }
}
List<Person> list = new List<Person>();
dgvPersona.DataSource= list.Select(data => new { data.Name, data.oDocument.Code }).ToList();
Upvotes: 1
Reputation: 223187
You need to select an anonymous type object (to project required fields) and then bind that to your gridview like:
var list = (from p in persons
select new
{
Name = p.Name,
DocumentCode = p.Document.Code
}).ToList();
dgvPersona.DataSource = list;
You may select the Id
as well and keep it in a hidden column in your gridview , so that later you can use it for record updating etc.
Upvotes: 2