I'm trying to get the number of items in a repeater whilst handling the OnItemDataBound
event. What I'm trying to achieve it quite simple; I'm trying to hide a certain label on the last item within a repeater. Currently I'm hooking into the ItemIndex
and Items.Count
, however as it's during the OnItemDataBound
, the index and count are incrementing together.
Here's what I've got so far:
Label myLabel = e.Item.FindControl<Label>("MyLabel");
if (myLabel != null)
{
// as the item index is zero, I'll need to check against the collection minus 1?
bool isLastItem = e.item.ItemIndex < (((Repeater)sender).Items.Count - 1);
myLabel.Visible = !isLastItem;
}
I know that I could cast the DataSource
to the collection of data items that were bound, however the OnItemDataBound
event handler is being used across multiple repeater, so I'll need something slightly more generic.
Could you do something along the lines of, having set Visible
to false by default:
if (e.Item.ItemIndex > 0)
{
var previousItem = ((Repeater)sender).Items[e.Item.ItemIndex - 1];
var previousLabel = previousItem.FindControl<Label>("MyLabel");
if (previousLabel != null)
{
previousLabel.Visible = true;
}
}
I'm not sure if this will work - I didn't know you could access repeater.Items
until I saw your code - but it seems plausible.