Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to databind using an anonymous type?

I think that's the right terminology...

Basically, I have a repeater control, and a Linq query that retrieves some items. Ordinarily I would databind straight to the query and use Eval to populate the template with the results.

However, it doesn't come through in quite the right format - for example, if EndDate is null (it's a DateTime?) then I want to substitute it with "Present". I am using only a couple of the properties in the query result objects.

I am wondering if there's a solution like:

[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>
like image 657
NibblyPig Avatar asked Feb 16 '11 13:02

NibblyPig


1 Answers

You have two options for declaring you result list:

  1. Use a non-generic ArrayList, or
  2. Use Enumerable.Repeat, ie. var anonList = Enumerable.Repeat(new { name="", enddate=""}, 0).ToList();
like image 60
erikkallen Avatar answered Oct 14 '22 03:10

erikkallen