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");
}
}
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.
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.
Eval(Object, String, String) Evaluates data-binding expressions at run time and formats the result as a string.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With