Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
noclist Avatar asked Sep 12 '14 18:09

noclist


People also ask

What is repeater control in ASP NET?

Repeater Controls in ASP.NET. The Repeater control is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. Repeater is a Data Bind Control.

How to use if else condition in itemtemplate of repeater?

IF ELSE statement is not supported in ItemTemplate of ASP.Net Repeater, but using Inline Expressions and Ternary Operator with the EVAL function, a simple IF ELSE condition can be easily implemented. In this article I will explain with an example, how to use IF ELSE condition in ItemTemplate of Repeater in ASP.Net using C# and VB.Net.

What is the use of repeater?

The Repeater control is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. Repeater is a Data Bind Control. Data Bind Controls are container controls.

How to edit or select data in repeater control?

The Repeater control has no built-in selection capabilities or editing support. You can use the ItemCommand event to process control events that are raised from the templates to the control. We have to use scriptlets for data access. Data Bind Control can display connected and disconnected model. Every DataBindControl implement collection.


1 Answers

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>
like image 149
Tushar Avatar answered Sep 19 '22 22:09

Tushar