Search code examples
c#asp.netdata-bindinghyperlinkrepeater

Adding hyperlinks to labels in certain cases, when dealing with databound repeater


Sounds a bit cluttered, but basically I have a databound repeater. On the ASP side, I have this:

<asp:Label ID="Label2" runat="server" Text='<%#Eval("uMessage") %>'></asp:Label>

I'm using the same template for 4 different datasets, and for 2 of them this should be a hyperlink and for the other 2 it shouldn't. So, I'm guessing you have to add a hyperlink programmatically in the code-behind? Has anyone ever done something like this?


Solution

  • Easiest way without all kinds of code-behind and therefor less code fragmentation, I would say you need a property that is set based on your condition prior to data binding.

    protected bool LinkVisible { get; set; }
    

    Then you just do this:

    <asp:Label ID="Label2" runat="server" Text='<%#Eval("uMessage") %>' Visible="<%# !LinkVisible %>"></asp:Label>
    <asp:HyperLink ID="Link" runat="server" Visible="<%# LinkVisible %>" ><%#Eval("uMessage") %></asp:HyperLink>
    

    This sets the Visible for either the Label or the HyperLink. Visible false means it won't even get rendered. In your markup you can see that there will be a label or a hyperlink and no special things popup from the code behind.

    You don't need to add the property LinkVisible, but can do the condition there too.