Aiju
Aiju

Reputation: 233

how to hide a div if a Listview is empty in asp .net

How should I hide the Attach div if the ListView2 is Empty.

<div id="Attach" class="AttachHead col-lg-12">
                    <h2>
                        Attachments</h2>
                </div>

<asp:ListView ID="ListView2" runat="server">
                    <ItemTemplate>
                        <a href='<%# String.Format("Download.aspx?Title={0}",Container.DataItem) %>' target="_blank">
                            <asp:Label ID="attach" runat="Server" Text='<%#Container.DataItem%>' CssClass="col-lg-4" />
                        </a>
                    </ItemTemplate>
                </asp:ListView>

Upvotes: 2

Views: 1264

Answers (2)

codeandcloud
codeandcloud

Reputation: 55210

If you do not want to alter your markup and do it in client-side, try this

$(document).ready(function () {
    $("#Attach").css("display", $(".col-lg-4").length ? "block" : "none");
});

The above code assumes that there is a PostBack on DataBind of the ListView. If you are using the unholy UpdatePanel change the DOM Ready event to pageLoad function like this

function pageLoad() {
    $("#Attach").css("display", $(".col-lg-4").length ? "block" : "none");
}

Upvotes: 0

Khaksar Weqar
Khaksar Weqar

Reputation: 425

Add runat="server" attribute to the div first.

<div runat="server" id="Attach" class="AttachHead col-lg-12"> <h2> Attachments</h2></div>

Then register the databound event of listview.

<asp:ListView ID="ListView2" runat="server" ondatabound="ListView2_DataBound">
                    <ItemTemplate>
                    <a href='<%# String.Format("Download.aspx?Title=    {0}",Container.DataItem) %>' target="_blank">
                        <asp:Label ID="attach" runat="Server" Text='<%#Container.DataItem%>' CssClass="col-lg-4" />
                    </a>
                </ItemTemplate>
            </asp:ListView>

and check with ListView2.items.count inside the databound method in codebehind like:

protected void ListView2_DataBound(object sender, EventArgs e)
{
  if (ListView2.Items.Count > 0)
        Attach.Visible = true;
    else
        Attach.Visible = false;
}

Upvotes: 3

Related Questions