DataList, Conditional statements in <ItemTemplate>?

Kevin picture Kevin · Nov 5, 2008 · Viewed 15.2k times · Source

I am trying to do the following in ASP.NET 3.5. Basically, I am binding a LINQDataSource to a DataList. There is a property called "Deleted" and if it is true, I want to display different markup. The following code throws errors:

<asp:DataList runat="server">
    <ItemTemplate>
        <% If CBool(Eval("Deleted")) Then%> 
            ...
        <% Else%>
            ...
        <% End If%>
    </ItemTemplate>
</asp:DataList>

Is this possible? If not, what are the alternatives?

Answer

Ben Griswold picture Ben Griswold · Jul 10, 2009

I might suggest keeping the code-front lean and writing out the desired text via a function result:

<asp:DataList runat="server">
    <ItemTemplate>
         <%# GetText(Container.DataItem) %>
    </ItemTemplate>
</asp:DataList>

And the code-behind:

protected static string GetText(object dataItem)
{        
    if (Convert.ToBoolean(DataBinder.Eval(dataItem, "Deleted"))
        return "Deleted";

    return "Not Deleted";
}

I hope it helps.