Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
    }
}
like image 556
John Avatar asked Jun 14 '11 00:06

John


People also ask

What is DataBinder Eval?

Eval (DataBinder. Eval) function is used to bind data in controls inside GridView, DataList, Repeater, DetailsView, etc. and using string. Format multiple values can be set to a single control. HTML Markup.

What is Eval in ASP net?

Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.

What does Eval do in c#?

Eval(Object, String, String) Evaluates data-binding expressions at run time and formats the result as a string.

What are Repeaters in ASP net?

The Repeater control is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. Repeater is a Data Bind Control. Data Bind Controls are container controls.


1 Answers

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.

like image 59
dariom Avatar answered Oct 26 '22 19:10

dariom