Error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control in repeater control

user244269 picture user244269 · Jun 4, 2014 · Viewed 23.3k times · Source

I am getting the following error

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control

but I am trying to write my code in ASP.NET REPEATER Control as

<%if (Eval("IsBreakPoint") == "1")
    { %>
        <tr>
            <td>
                <asp:Label ID="lblCategory" runat="server" Text='<%#Eval("Category") %>'></asp:Label>
            </td>
            <td colspan="27">
            </td>
       </tr>
    <%} %>

Please help

Answer

Merenzo picture Merenzo · Jun 4, 2014

The <% if %> statement doesn't support databinding.

For conditional display, I always try to databind to the Visible property of a single server control.

In a case like yours involving a block of markup (rather than a single server control), I'd wrap that block in an <asp:PlaceHolder> control as follows:

<asp:PlaceHolder ID="CategoryPlaceHolder" runat="server" Visible='<%# Eval("IsBreakPoint") == "1") %>'>

    <tr>
        <td>
            <asp:Label ID="lblCategory" runat="server" Text='<%#Eval("Category") %>'></asp:Label>
        </td>
        <td colspan="27">
        </td>
   </tr>

</asp:PlaceHolder>

Or if you aren't really using that label server-side:

<asp:PlaceHolder ID="CategoryPlaceHolder" runat="server" Visible='<%# Eval("IsBreakPoint") == "1") %>'>

    <tr>
        <td>
            <%# Eval("Category") %>
        </td>
        <td colspan="27">
        </td>
   </tr>

</asp:PlaceHolder>

Or more readable still: if you can define the ItemType property for the Repeater, then you will get strong typing and Intellisense at design-time (this would be my recommended approach):

<asp:PlaceHolder ID="CategoryPlaceHolder" runat="server" Visible='<%# Item.IsBreakPoint == "1") %>'>

    <tr>
        <td>
            <%# Item.Category %>
        </td>
        <td colspan="27">
        </td>
   </tr>

</asp:PlaceHolder>

Take care to use single quotes around the Visible value when that expression contains double quotes. (Ahh, as you have already done with the Label.Text property.)