Repeater displays a list of items with a custom template. Our repeater shows the top 10 items. Instead of regular pagination, we have a Show More
link. On clicking the link, we show all the remaining items.
We create a repeater with HeaderTemplate
, ItemTemplate
and FooterTemplate
. HeaderTemplate
begins an unordered list using the ul
tag. ItemTemplate
uses the li
tag to show a list of items. FooterTemplate
has the Show More
link. It also ends the unordered list.
<asp:Repeater ID="rpt" runat="server" DataSourceID="sql" OnItemDataBound="rpt_ItemDataBound"> <HeaderTemplate> <ul id="list"> </HeaderTemplate> <ItemTemplate> <li id="listItem" runat="server"> <%# Eval("au_lname") %> </li> </ItemTemplate> <FooterTemplate> </ul> <a id="show" href="javascript:show();">Show All</a> <a id="hide" href="javascript:hide();" style="display:none;">Hide</a> </FooterTemplate> </asp:Repeater> <asp:SqlDataSource ID="sql" runat="server" ConnectionString="<%$ ConnectionStrings:Pubs %>" SelectCommand="SELECT au_lname FROM Authors"> </asp:SqlDataSource>
Bind the Repeater to a SqlDataSource
. Handle the OnItemDataBound
event. In the handler, show only the top 10 items and hide the remaining. From the 11th item onwards, use the style, display: none
to hide the items.
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemIndex >= 10) { HtmlGenericControl li = e.Item.FindControl("listItem") as HtmlGenericControl; li.Attributes.Add("style", "display: none;"); } }
We need some Javascript for Show and Hide buttons. In the show function, show the remaining items. In the hide function, we hide all items other than the top 10.
function show() { var list = document.getElementById('list').getElementsByTagName("li"); for (var i = 0; i < list.length; i++) { if (i >= 10) { list[i].style.display = 'block'; } } document.getElementById('hide').style.display = 'inline'; document.getElementById('show').style.display = 'none'; } function hide() { var list = document.getElementById('list').getElementsByTagName("li"); for (var i = 0; i < list.length; i++) { if (i >= 10) { list[i].style.display = 'none'; } } document.getElementById('hide').style.display = 'none'; document.getElementById('show').style.display = 'inline'; }
As you can see, Repeater is a powerful control with custom template. For our simple list, we have used an unordered list. But, we can create more complex layout with div
tag.