Equivalent of Eval("field") in ASP.NET Repeater ItemDataBound event?

John picture John · Jun 14, 2011 · Viewed 12.8k times · Source

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");
    }
}

Answer

dariom picture dariom · Jun 14, 2011

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.