Tuesday, July 15, 2008

RepeatColumns in ListView

The last major feature of the ListView is the ability to group data into subsets, much like the DataList control provides. The DataList is a tabular control that renders a single row of data in each cell of the rendered table. You control how many rows of the underlying dataset are grouped into a single table row by setting the RepeatColumns property.

Since the ListView is not constrained to render as a table, it needs a more generic way of specifying groups of items to be rendered together, which is what GroupTemplate does. Pic below shows the relationship among the LayoutTemplate, GroupTemplate, and ItemTemplate elements within a ListView. The GroupTemplate lets you specify the surrounding HTML for every n elements in the underlying dataset, where n is specified by the GroupItemCount property of the ListView.

 

When you use a GroupTemplate within a ListView, you won't specify a control with an ID of itemPlaceholder within your LayoutTemplate—that control now needs to be in your GroupTemplate. Instead, you will specify a control with an ID of groupPlaceholder in the LayoutTemplate (you can change the control ID by setting the GroupPlaceholderID property of the ListView) to describe where the contents of the GroupTemplate should be injected for each n items encountered in the underlying dataset.

Here is example how to use GroupTemplate in ListView

<asp:ListView ID="ListView1" runat="server" OnPagePropertiesChanging="ListView1_PagePropertiesChanging" GroupItemCount="2" DataKeyNames="CourtID">
<LayoutTemplate>
<asp:PlaceHolder id="groupPlaceholder" runat="server"/>
</LayoutTemplate>
<GroupTemplate>
<table>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</GroupTemplate>
<ItemTemplate>
<td>
test<%# Eval("CourtID") %>
</td>
</ItemTemplate>
/asp:ListView>





This is very similar to what you could do with a DataList, but because you are working with a ListView, you can just as easily add both pagination and sorting as you did earlier with your grid rendering, a task that would be rather daunting with the DataList. The code download for this article contains an example that implements both pagination and sorting for your reference.

No comments: