If statement in repeaters ItemTemplate

Vivendi picture Vivendi · Jun 18, 2013 · Viewed 40k times · Source

I'm using an ASP.NET Repeater to display the contents of a <table>. It looks something like this:

<table cellpadding="0" cellspacing="0">
    <asp:Repeater ID="checkboxList" runat="server" OnItemDataBound="OnCheckboxListItemBound">
        <ItemTemplate>
            <tr id="itemRow" runat="server">
                <td>
                    Some data
                </td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>
</table>

It works fine, but i'd like to have an if() statement inside the ItemTemplate so i can conditionally determine if i want to print out a <tr> tag.

So i'd like to have something like this:

<table cellpadding="0" cellspacing="0">
    <asp:Repeater ID="checkboxList" runat="server" OnItemDataBound="OnCheckboxListItemBound">
        <ItemTemplate>

            <% if ( (CurrentItemCount % 2) == 0 ) { %?>
            <tr id="itemRow" runat="server">
            <% } %>
                <td>
                    Some data
                </td>
            <% if ( (CurrentItemCount % 2) == 0 ) { %?>
            </tr>
            <% } %>
        </ItemTemplate>
    </asp:Repeater>
</table>

Is there some way i can achieve this?

PS. The CurrentItemCount is just made up. I also need a way to get the current item count inside that if() statement. But i only seem to be able to get it from <%# Container.ItemIndex; %>, which can't be used with an if() statement?

Answer

maets picture maets · May 5, 2015

Another way of doing this (if performance is not a problem):

<ItemTemplate>
  <!-- "If"  -->
  <asp:PlaceHolder runat="server" Visible="<%# MyCondition %>">
    <tr><td></td></tr>
  </asp:PlaceHolder>  
  <!-- "Else" -->
  <asp:PlaceHolder runat="server" Visible="<%# !MyCondition %>">
    <tr><td></td></tr>
  </asp:PlaceHolder>
</ItemTemplate>