I want to show certain parts of an ItemTemplate
based according to whether a bound field is null. Take for example the following code:
(Code such as LayoutTemplate have been removed for brevity)
<asp:ListView ID="MusicList" runat="server">
<ItemTemplate>
<tr>
<%
if (Eval("DownloadLink") != null)
{
%>
<td>
<a href="<%#Eval("DownloadLink") %>">Link</a>
</td>
<%
} %>
</tr>
</ItemTemplate>
</asp:ListView>
The above gives the following run-time error:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
So how can put some conditional logic (like the above) in an 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.
If you have 2 different structure that are to be rendered according to a condition then use panels
<asp:ListView ID="MusicList" runat="server">
<ItemTemplate>
<tr>
<asp:Panel ID="DownloadNull" runat="server" Visible="<%# Eval("DownloadLink") == null %>" >
<td> Album Description BlaBlaBla <img src="../images/test.gif"> </td>
</asp:Panel>
<asp:Panel ID="DownloadNotNull" runat="server" Visible="<%# Eval("DownloadLink") != null %>" >
<td> Album Description BlaBlaBla <img src="../images/test.gif">
<a href='<%# Eval("DownloadLink")' >Download</a>
.....
</td>
</asp:Panel>
</tr>
</ItemTemplate>
</asp:ListView>
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