Binding List of Custom Class to GridView or ListView Control
Scenario:
I am not going to write a lot but just show some code. Say you have a class(e.g. Customer) that itself exposes another class(e.g.Person) as its property. Now you want to take a List of Customer class and bind it to databound controls like GridView Or ListView ?
public class Customer
{
public Customer()
{
this.CustPerson = new Person();
}
public int id { get; set; }
public Person CustPerson { get; set; }
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Binding it to GridView:
Here is code that populates GridView with list of customers:
List<Customer> customerlist = new List<Customer>();
for (int i = 0; i <= 4; i++)
{
Customer cust = new Customer();
cust.id = i;
cust.CustPerson.FirstName = "John-" + i.ToString();
cust.CustPerson.LastName = "Doe-" + i.ToString();
cust.CustPerson.Age = 20 + i;
customerlist.Add(cust);
}
GridView1.DataSource = customerlist;
GridView1.DataBind();
Problem:
But say if your GridView is set to AutoGenerateColumns=true, which is default, then GV will show only the "id" column and the columns pertaining to Person are kind of lost.
How to access that inner class (e.g. Person here) ?
Answer to that is you need to explicitly cast the DataItem.Below is sample how you will display FirstName.
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# ((Customer)Container.DataItem).CustPerson.FirstName %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Similarly adding other columns the view will be something like below.
To get reference to DataItem in code-behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType== DataControlRowType.DataRow)
{
Customer drv = (Customer)e.Row.DataItem;
}
}
Conclusion:
Same concept goes with other databound controls like ListView. Hope it helps and let me know if you have any questions.