Is it possible to use data binding using an anonymous type?

I think the correct terminology ...

Basically, I have a repeater control and a Linq query that retrieves some elements. Normally, I would bind the data directly to the query and use Eval to populate the template with the results.

However, it does not pass in the correct format - for example, if EndDate is null (is it DateTime?), Then I want to replace it with "Present". I use only a couple of properties in the query result objects.

I am wondering if there is such a solution as:

[pseudo madeup code] var query = getResults(); List<anonymous> anonList = new List(); foreach (var q in query) { string myEndDate = ""; if (q.EndDate.HasValue) { myEndDate = q.EndDate.ToString(); } else { myEndDate = "Present"; } anonList.items.add(new { name=q.name, enddate=myEndDate }; } repeater.Datasource = anonList; 

then

 <div><%#Eval("enddate")%></div> 
+6
c # repeater
source share
3 answers

You have two options for declaring a list of results:

  • Use not a generic ArrayList , either
  • Use Enumerable.Repeat , i.e. var anonList = Enumerable.Repeat(new { name="", enddate=""}, 0).ToList();
+2
source share

Yes, you can bind to anonymous types, but your code will need to be slightly modified to generate a sequence of these types:

 repeater.DataSource = getResults() .Select(q => new { name = q.name, enddate = (q.EndDate.HasValue) ? q.EndDate.ToString() : "Present" }); 
+1
source share

You can take a sample of Andrews:

 repeater.DataSource = getResults() .Select(q => new { name = q.name, enddate = (q.EndDate.HasValue) ? q.EndDate.ToString() : "Present" }); 

but instead of evaluating the enddate inline, you call the function:

 repeater.DataSource = getResults() .Select(q => new { name = q.name, enddate = GetEndDate(q)}); private void GetEndDate(TypeOfQ q) { return (q.EndDate.HasValue) ? q.EndDate.ToString() : "Present"; } 

Is that what you think?

Regards, Chris

+1
source share

All Articles