ASP.Net: Conditional Logic in a ListView's ItemTemplate ASP.Net: Conditional Logic in a ListView's ItemTemplate asp.net asp.net

ASP.Net: Conditional Logic in a ListView's ItemTemplate


What about binding the "Visible" property of a control to your condition? Something like:

<asp:ListView ID="MusicList" runat="server">   <ItemTemplate>    <tr runat="server" Visible='<%# Eval("DownloadLink") != null %>'>        <td>            <a href='<%#Eval("DownloadLink") %>'>Link</a>        </td>    </tr>   </ItemTemplate></asp:ListView>


To resolve "The server tag is not well formed." for the answers involving visibility, remove quotes from the Visible= parameter.

So it will become:

<tr runat="server" Visible=<%# Eval("DownloadLink") != null ? true : false %>>


I'm not recommending this as a good approach but you can work around this issue by capturing the current item in the OnItemDataBound event, storing it in a public property or field and then using that in your conditional logic.

For example:

<asp:ListView ID="MusicList" OnItemDataBound="Item_DataBound" runat="server">    <ItemTemplate>        <tr>            <%                if (CurrentItem.DownloadLink != null)                {            %>            <td>                <a href="<%#Eval("DownloadLink") %>">Link</a>            </td>            <%                } %>        </tr>    </ItemTemplate></asp:ListView>

And on the server side add the following code to your code behind file:

public MusicItem CurrentItem { get; private set;}protected void Item_DataBound(object sender, RepeaterItemEventArgs e){   CurrentItem = (MusicItem) e.Item.DataItem;}

Note that this trick will not work in an UpdatePanel control.