I want to get at the item that is being data bound, during the ItemDataBound event of an asp:repeater.
I tried the following (which was an unaccepted answer in a stackoverflow question):
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Object dataItem = e.Item.DataItem;
...
}
but e.Item.DataItem
is null.
How can I access the item being data bound during the event called ItemDataBound. I assume the event ItemDataBound happens when an item is being data bound.
I want to get at the object so I can take steps to control how it is displayed, in addition the object may have additional helpful properties to let me enrich how it is displayed.
Answer
Tool had the right answer. The answer is that e.Item.Data
is only valid when e.Item.ItemType
is (Item, AlternatingItem). Other times it is not valid. In my case, I was receiving ItemDataBound events during header (or footer) rows, where there is no DataItem:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// if the data bound item is an item or alternating item (not the header etc)
if (e.Item.ItemType != ListItemType.Item &&
e.Item.ItemType != ListItemType.AlternatingItem)
{
return;
}
Object dataItem = e.Item.DataItem;
...
}
I just wanted to add that I did accomplished this by doing the following:
Use dynamic
For repeater
Can be modified to:
If you're dealing with an asp:ListView, you can do something like this:
(The title of the question doesn't mention an asp:repeater.. so I thought it might be helpful to post the code for an asp:listview)
For a repeater with a custom template binding; you can use the following template. I used this to create a table which breaks down each data item into two rows for print view.
Right off the bat I would have to guess you need this:
After all, the item itself could be representing a header or footer row.