8

I want to do the equivalent of Eval("field") in an ASP.NET repeater ItemDataBound Event but am not sure what to cast e.Item.DataItem as. The data source type could vary as this is reusable code in a custom control. So how can I access a field in e.Item.DataItem by field name (a string)?

Ideally I want to do something like:

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
    {
        xxx item = (xxx)e.Item.DataItem;
        string fieldValue = item("fieldname");
    }
}
John
  • 139
  • 1
  • 1
  • 6

2 Answers2

9

If you don't know what the type is at compile time your only option is to treat is as an object (which is the default return type for the DataItem property).

You could try using:

object item = DataBinder.Eval(e.Item.DataItem, "fieldname");

You're still stuck with an object at the end of that call, but (assuming the call is successful) you'll know that item has a property named fieldname. I don't know if that helps. Perhaps update your question with more detail about what you're trying to do.

dariom
  • 4,245
  • 26
  • 40
  • DataBinder.Eval(e.Item.DataItem, "fieldname") was the information I needed... Didn't realise I could do that in the code behind. Thanks. – John Jun 14 '11 at 01:10
0

instead of xxx item = (xxx)e.Item.DataItem;

write it:

var item = e.Item.DataItem;

or may be:

object item = e.Item.DataItem;
Amr Elgarhy
  • 59,046
  • 67
  • 178
  • 291