Tuesday, February 15, 2011

[ASP.NET]–How to dynamically hide ListView LayoutTemplate headings

This is a very web forms specific technique that I needed to use on a project recently. I had a ListView control which had a LayoutTemplate similar to this:

<LayoutTemplate>
        <table class="staffList">
            <thead>
                <tr>
                    <th>
                        Name
                    </th>
                    <th runat="server" id="CountHeading">
                        Count
                    </th>
                </tr>
            </thead>
            <div id="itemPlaceholder1" runat="server">
            </div>
</LayoutTemplate>

I was hosting this inside a User Control where I had a property that would turn the display of the Count column on and off (named ‘ShowDetails’). It was easy for me to not display the count data for each Name, but the headings would stay there.

What I needed to do was add the runat=”server” id=”CountHeading” attributes to the th element in my LayoutTemplate as above, and then subscribe to the OnLayoutCreated event in the ListView

OnLayoutCreated="OnLayoutCreated"

Then in the OnLayoutCreated method I did the following:

protected void OnLayoutCreated(object sender, EventArgs e)
{
    if (!this.ShowDetails)
    {
        this.StaffListView.FindControl("CountHeading").Visible = false;
 
    }
}

This uses the FindControl method to find the control by its ID. Because I added runat=”server” to the th tag, it becomes a server side control and can be modified in such a way.

2 comments:

Anonymous said...

Great stuff - helped me with my problem with being about to hide laytouttemplate labels

Anonymous said...

Thank you so much.