Anonymous type in Repeater DataBound event
Asked Answered
B

2

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

Bootleg answered 31/7, 2009 at 12:13 Comment(0)
N
23

You can use DataBinder.Eval:

string repName = (string)DataBinder.Eval(e.Item.DataItem, "RepName");
string target = (string)DataBinder.Eval(e.Item.DataItem, "Target");
Nth answered 31/7, 2009 at 12:19 Comment(0)
P
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;
Pentahedron answered 12/8, 2010 at 12:25 Comment(2)
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 thisKourtneykovac
In that case you should probably do something like string repName = targetInfo.RepName; if (repName == "") { ... }Pentahedron

© 2022 - 2024 — McMap. All rights reserved.