Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement in repeaters ItemTemplate

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?

like image 778
Vivendi Avatar asked Jun 18 '13 12:06

Vivendi


2 Answers

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>
like image 62
maets Avatar answered Nov 15 '22 18:11

maets


If you're trying yo make a 2 columns table this could do the trick

<%# Container.ItemIndex % 2 == 0 ? "<tr class='itemRow'>" : "" %>
    <td>
       Some data
    </td>
<%# Container.ItemIndex % 2 != 0 ? "</tr> : "" %>

Changed a couple of things: id="itemRow" for all rows would cause repeated ids what is not allowed.

Removed runat="server" since doesn't make sense on this context.

like image 42
Claudio Redi Avatar answered Nov 15 '22 19:11

Claudio Redi