Search code examples
asp.netrepeater

ASP.Net repeater control - using conditional statements


I am trying to use an if statement inside of a repeater control and receiving an InvalidOperationException on the if.

What I'm trying to do is run a block of code inside the repeater only if the current item has a UserType that is set to Admin.

     <asp:Repeater ID="rptSingleValueHeaders" runat="server">
         <ItemTemplate>
             <% if (Eval("UserType").ToString() == "Admin") { %>
                 <div>
                     do stuff here
                 </div>
            <% } else { %>
                 <div>
                     do other stuff
                 </div>
            <% } %>
         </ItemTemplate>
     </asp:Repeater>

My datasource is defined on the aspx.cs and contains a property named UserType which is of type string. Let me know if I need to provide any more details. Thank you.


Solution

  • You could use server side visibility:

    <ItemTemplate>
        <div runat="server" visible='<%# (Eval("UserType").ToString() == "Admin") %>'>
            I show this HTML
        </div>
        <div runat="server" visible='<%# (Eval("UserType").ToString() != "Admin") %>'>
            I show this other HTML
        </div>
    </ItemTemplate>