4

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Programer
  • 1,005
  • 3
  • 22
  • 46

1 Answers1

0

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">
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • But this is Server sided. I need to use it on the Page side like this <%if (#Item.BonusType==Enum.BounusTypes.50Percent){%> you get 50% off!<%}%> – Programer Dec 10 '14 at 12:44
  • @Programer: that is also executed on serverside. You can get the same code in a much more readable manner. But you have to show more of what you're trying to do and the controls involved, otherwise i cannot show you a complete example. – Tim Schmelter Dec 10 '14 at 12:45
  • I know, But I want it to be on the dynamic page not in a function. how do I print to the html if condition is valid in you way? – Programer Dec 10 '14 at 12:46
  • @Programer: then you have to wait for another answer. I don't know and don't want to know how you can do something like that with inline aspx. That's more like classic ASP than ASP.NET. – Tim Schmelter Dec 10 '14 at 12:48