Reputation: 1303
Ok, let's imagine I have an object like this:
public class User {
public int ID { get; set; }
public String Name { get; set; }
public String Surname { get; set; }
public String Description { get; set; }
public Location Location { get; set; }
}
Notice that the last property, is a Location type object. Let's see the Location object:
public class Location {
public String ID { get; set; }
public String Address { get; set; }
public String PostCode { get; set; }
}
Now I want to show a list of users in a gridview but instead of feeding it with a datareader or any data object, I want to use a List of Users Collection, so I call a method that gives me a List collection and databind the gridview like this:
gvUsers.DataSource = getUsers(); // This returns a List<User> collection.
gvUsers.DataBind();
Now, I've used some BoundFields and Templatefields to show the data and it works without problems, like this:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Surname">
<ItemTemplate>
<asp:Label ID="lbSurname" runat="server" Text='<%# Eval("Surname") %>'></asp:Label>
<asp:HiddenField ID="hdnUserId" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The problem comes if I try to access the Location object properties, imagine this in the template field:
<asp:HiddenField ID="hdnLocationName" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "Location.PostCode") %>' />
That doesn't work.
I don't know if there is a way of doing that to show it using a template field. I also wonder if there is a way of doing it using a BoundField.
If it cannot be done just using the FrontEnd, can be done in the Backend in the gridView databound somehow? Should I use LINQ and set it on the select instead?
Upvotes: 3
Views: 2297
Reputation: 101
Much cleaner solution is to override ToString method in location to represent description.
Upvotes: 0
Reputation: 6409
The Law of Demter applies. In short, you'll have to make Postcode a property of user if you want to bind to it like that.
This page gives a nice example of Law of Demeter.
Upvotes: 1
Reputation: 67115
The best that you could do AFAIK is add a property that merely pulls the value out of Location
. Something like this:
public class User {
public int ID { get; set; }
public String Name { get; set; }
public String Surname { get; set; }
public String Description { get; set; }
public Location Location { get; set; }
public String LocationPost {get{return Location.Post;}}
}
Upvotes: 1