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.
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With