asp.net Repeater - get Reference to current Item

3.6k views Asked by At

I am using Asp.net 4.5, C#. I have a reapter that has some DataSource Bind to it:

  <asp:Repeater ItemType="Product" ID="ProductsArea" runat="server">
            <HeaderTemplate></HeaderTemplate>
            <ItemTemplate>
                ...  
            </ItemTemplate>
            <FooterTemplate></FooterTemplate>
        </asp:Repeater>    

Inside this repeater, I would like a refrence to the current Iterated Item. I know I can use <%#Item%> and that I can Use <%#Container.DataItem%>. If I want to get to a field, I can use <%#Item.fieldName%> or Eval it.

But I want to make a condition on a field, How can I get the refrence to the #Item in order to do something like this:

<% if (#Item.field>3)%>, <%if (#Container.DataItem.field<4)%> 

I would acautley would like to have a refrence like this <%var item = #Item%> and than to use it whenever I need.

Ofcourse the syntax above is invalid, How to achieve this properley?

1

There are 1 answers

4
Tim Schmelter On

I'd use ItemDataBound instead. That makes the code much more readable, maintainable and robust(compile time type safety).

protected void Product_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        // presuming the source of the repeater is a DataTable:
        DataRowView rv = (DataRowView) e.Item.DataItem;
        string field4 = rv.Row.Field<string>(3); // presuming the type of it is string
        // ...
    }
}

Cast e.Item.DataItem to the actual type. If you need to find a control in the ItemTemplate use e.Item.FindControl and cast it appropriately. Of course you have to add the event-handler:

<asp:Repeater OnItemDataBound="Product_ItemDataBound" ItemType="Product" ID="ProductsArea" runat="server">