0
votes

I have a repeater showing product stocks. I want show if no stock "Out of stock". If present show stock amount and unit.

I tried the following ways:

<%#Convert.ToInt32(Eval("AMOUNT")) == 0 ? "Out of stock" : %><%#Eval("AMOUNT") %> <%#Eval("UNIT") %>

and

<% if ( Convert.ToInt32(Eval("AMOUNT")) == 0) { %>
    <asp:Label ID="Label1" runat="server" Text='Out of stock'></asp:Label>
<%} else { %>
    <asp:Label ID="Label2" runat="server" Text='<%#Eval("AMOUNT") %>'></asp:Label>
<% } %>

I am getting this error in this method: System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

Maybe there is a simple solution but I can't find. Thanks.

1

1 Answers

1
votes

This if condition obviously doesn't support data binding, hence InvalidOperationException occurs:

<% if ( Convert.ToInt32(Eval("AMOUNT")) == 0) { ... } %>

Since the if condition has two blocks of markup (with else condition), you can use two asp:PlaceHolder controls as replacement with different visibility condition (one equals to zero and other is greater than zero):

<asp:PlaceHolder ID="AmountPlaceHolder1" runat="server" Visible='<%# Eval("AMOUNT") == 0 %>'>
    <asp:Label ID="Label1" runat="server" Text='Out of stock'></asp:Label>
</asp:PlaceHolder>
<asp:PlaceHolder ID="AmountPlaceHolder2" runat="server" Visible='<%# Eval("AMOUNT") > 0 %>'>
    <asp:Label ID="Label2" runat="server" Text='<%# Eval("AMOUNT") %>'></asp:Label>
</asp:PlaceHolder>

Or use strongly-typed RepeaterItem.ItemType property instead of Eval:

<asp:PlaceHolder ID="AmountPlaceHolder1" runat="server" Visible='<%# Item.Amount == 0 %>'>
    <asp:Label ID="Label1" runat="server" Text='Out of stock'></asp:Label>
</asp:PlaceHolder>
<asp:PlaceHolder ID="AmountPlaceHolder2" runat="server" Visible='<%# Item.Amount > 0 %>'>
    <asp:Label ID="Label2" runat="server" Text='<%# Item.Amount %>'></asp:Label>
</asp:PlaceHolder>