How to display subobject property when databinding from a list of objects in c #

Ok, suppose 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; }
}

Note that the last property is an object of type Location. Let's look at 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 the list of users in gridview , but instead of loading it using a datareader or any data object, I want to use the List of Users collection, so I call the method that gives me the List and databind gridview as follows:

gvUsers.DataSource = getUsers(); // This returns a List<User> collection.
gvUsers.DataBind();

Now I used some BoundFields and Templatefields to display the data, and it works without problems, for example:

<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 occurs if I try to access the properties of the Location object, imagine this in the template field:

<asp:HiddenField ID="hdnLocationName" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "Location.PostCode") %>' />

This does not work.

, , , . , , BoundField.

FrontEnd, - Backend gridview? LINQ select?

+3
3

. , Postcode , .

.

+1

, AFAIK, - , Location. - :

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;}}
}
+1

- ToString .

0

All Articles