Monday, October 23, 2006

Data Binding Child Object Properties

I don't know why but I always have trouble remembering the syntax to databind child object properties. When using a GridView, a TemplateField must be used to get the values from the child object as a BoundField do not work correctly in this scenario.

In order to bind to properties of a Customer object which is a property of another class, use the syntax below:

<%# ((Customer)Eval("Customer")).ID %>
<%# ((Customer)Eval("Customer")).Name %>

Note that a null customer property value will cause problems with this approach and don't forget to add the a reference to the Customer class using the Import directive.

<%@ Import namespace="MyNamespace.Customer" %>

Another fiddly issue can be embedding a nested data control such as Repeater within a GridView column and databinding to a child object.

<asp:Repeater ID="rpt" runat="server" DataSource='<%# ((Customer)Container.DataItem).Address%>'>
<ItemTemplate><%# Container.DataItem %></ItemTemplate>

1 comment:

David Verrière said...

You cans use this syntaxe :