Search code examples
c#asp.netlistviewelementvisible

hiding an element inside a listview


I'm trying to hide an anchor inside my ListView by using visible='false' , but I have noticed that it is not working. I have also tried hiding the element using css but it's also not working. I have checked and there are no javascript errors or code behind errors.

This is what I did:

       //inside ItemTemplate in ListView
    <td>
    <a runat="server"  id="selectionAnchor" href='Somelocation' visible='<%# (Convert.ToBoolean(uoshowHiddenField.Value)) %>' >  Edit</a>
 </td>

I placed my uoShowHiddenField above the listview :

 <asp:HiddenField ID="uoShowHiddenField" runat="server" Value="false" /> 

but whenever I inspect the element in the browser it shows up like this:

<a href="Somelocation" id="selectionAnchor"> Edit</a>

I have also tried using this method to no avail:

style=' <%# (uoShowHiddenField.Value == "true") %> ? " ": "display:none;" %> '

Am I doing something wrong? It has taken alot of my time and I am really frustrated as to why it's not working.


Solution

  • Very rough rundown, but this is how you would do it. Remember to include the OnItemDataBound="" event binding to the ListView in the .aspx code:

    Code behind:

    As you are using a plain old HTML hyperlink, you will have to use the HtmlGenericControl class to target the control

    protected void SampleListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
           if(uoShowHiddenField.Value == "true") {
              HtmlGenericControl hyperlink = (HtmlGenericControl)e.item.FindControl("selectionAnchor");
              hyperlink.Visible = false;
           }
        }
    }
    

    ASPX:

    <asp:ListView ID="SampleListView" OnItemDataBound="SampleListView_ItemDataBound" runat="server">
            <ItemTemplate>
                <a runat="server" ID="selectionAnchor">Link</a>
            </ItemTemplate>
        </asp:ListView>
    

    I tend to go for ItemDataBound as it aids separation of concerns and reinforces the whole code behind / client code rule.