10

I'm setting the DataSource of an ASP.NET repeater as follows:

rptTargets.DataSource = from t in DB.SalesTargets select new { t.Target, t.SalesRep.RepName };

Now, in the repeater's OnDataBound event, how can I retrieve the RepName and Target properties from the anonymous type contained in e.Item.DataItem?

Many Thanks

staterium
  • 1,980
  • 2
  • 20
  • 32

2 Answers2

23

You can use DataBinder.Eval:

string repName = (string)DataBinder.Eval(e.Item.DataItem, "RepName");
string target = (string)DataBinder.Eval(e.Item.DataItem, "Target");
Richard Szalay
  • 83,269
  • 19
  • 178
  • 237
13

I know this question has been answered over a year ago, but I've just found a .NET 4.0 solution for this problem.

When you bind your anonymous type to a repeater, you can access the properties in the OnDataBound event like this:

dynamic targetInfo = e.Item.DataItem as dynamic;

string repName = targetInfo.RepName;
string target = targetInfo.Target;
Kristof Claes
  • 10,797
  • 3
  • 30
  • 42
  • What if i have to put a condition on he member from targetInfo like if(targetinfo.RepName =="") then? how to put a condition ? because it gives me an exception that it doesn't have any type like this – LojiSmith Feb 18 '13 at 08:17
  • In that case you should probably do something like `string repName = targetInfo.RepName; if (repName == "") { ... }` – Kristof Claes Sep 19 '13 at 13:00