Ryan
Ryan

Reputation: 3982

Access object properties from lists via asp .net object data source

If I have an ObjectDataSource that returns Person who has a property FavoutieColoirs as a List, can I access one of those Colours for display, via some notation in the ASP markup?

i.e. if Person has had a Name property, I can use

<%# DataBinder.Eval(Container.DataItem, "Name") %>

Can I use something like

<%# DataBinder.Eval(Container.DataItem, "Colours[0]") %>

Or maybe even

<%# DataBinder.Eval(Container.DataItem, "Colours.Select(x => x.ColourName == 'Blue')" %>

(Pretty sure the last one doesn't work, but I'm hoping there's some way to implement the second).

If I can't do that and want to diaply the 'first item in a List' (say) do I have to add a method to Person for 'FirstFavouriteColour' that returns a single item?

Upvotes: 1

Views: 926

Answers (1)

Simon Mourier
Simon Mourier

Reputation: 139095

The official documentation at DataBinder.Eval Method (Object, String) is quite clear about this:

Expression: The navigation path from the container object to the public property value to be placed in the bound control property. This must be a string of property or field names separated by periods, such as Tables[0].DefaultView.[0].Price in C# or Tables(0).DefaultView.(0).Price in Visual Basic

So the second expression should work fine if Colours has an indexer (this[int index]) property defined.

Upvotes: 2

Related Questions