<asp:Repeater> Control

An <asp:Repeater> control displays a repeated list of data items that are bound to it. Like the GridView, it is designed for convenient display of records from a database or other relational data source.

The Repeater control is based on the use of templates. A template is a model for output display using binding expressions, server controls, and HTML tags to structure the output. Its use is very similar to that of a TemplateField in a GridView. The general format for coding a Repeater control is shown below. Not all sections of the control are needed to produce simple data listings.

<asp:Repeater id="value" Runat="Server"
  DataSourceID="id">

  <HeaderTemplate>
    HTML and binding expressions
  </HeaderTemplate>

  <ItemTemplate>
    HTML and binding expressions
  </ItemTemplate>

      <AlternatingItemTemplate>
        HTML and binding expressions
      </AlternatingItemTemplate>

      <SeparatorTemplate>
        HTML and binding expressions
      </SeparatorTemplate>

  <FooterTemplate>
    HTML and binding expressions
  </FooterTemplate>

</asp:Repeater>
Figure 8-1. General format for <asp:Repeater> control.

Binding to a Repeater Control

A Repeater is bound to a data source to display its contents. As in the case of a GridView, a Repeater can be linked to a data source control such as an AccessDataSource. As in the case of using TemplateField columns in a GridView, data fields are bound to the Repeater through individual data field binding expressions.

In its simplest format, the Repeater requires only an <Item Template> to describe its output format. Within this template, text, HTML, and binding expressions are coded to provide a model for formatting the data. In the following example, output is formatted as repeating lines of data, each line composed of selected data fields from the Products table of the eCommerce.mdb database.

BU1111, Microsoft Office Professional 2003, 419.99
BU2222, WordPerfect Office 12, 210.25
BU3333, Project 2003, 519.99
DB1111, Access 2003, 194.95
DB2222, SQL Server 2000 Standard, 1989.95
DB3333, FileMaker Pro 6, 275.95
DP1111, FrameMaker 7.0, 799.95
DP2222, QuarkXPress 6.0, 869.95
GR1111, Photoshop CS, 589.95
GR2222, Illustrator CS, 359.95
GR3333, Studio/MX 2004, 969.95
GR4444, Flash/MX 2004, 499.99
GR5555, Creative Suites Premier 1.1, 1109.99
OS1111, Windows XP Home, 49.95
OS2222, Windows XP Professional, 139.95
OS3333, Windows Server 2003, 949.95
WB1111, HomeSite 5.0, 94.95
WB2222, Dreamweaver MX 2004, 379.95
WB3333, FrontPage 2003, 179.95
WB4444, Visual Studio .NET Professional, 749.88
Figure 8-2. Using a Repeater to display a database recordset.
<asp:AccessDataSource id="Products" Runat="Server"
  DataFile="../Databases/eCommerce.mdb"
  SelectCommand="SELECT * FROM Products"/>
	
<asp:Repeater id="ProductsTable" DataSourceID="Products" Runat="Server">
  <ItemTemplate>
    <%# Eval("ItemNumber") %>, 
    <%# Eval("ItemName") %>, 
    <%# Eval("ItemPrice") %><br/>
  </ItemTemplate>
</asp:Repeater>
Listing 8-1. Binding a data source to a Repeater.

The <ItemTemplate> section of the control specifies the data items to be displayed along with any HTML formatting for the data. This template is a model for a single output line, and when data are bound to the Repeater the template is repeated for as many records as appear in the recordset.

Data displays inside an ItemTemplate are given by binding expressions in the following format.

<%# Eval("fieldname") %>
Figure 8-3. General format for data binding expression for Repeater control.

The fieldname is the name of a field from the data source whose value is displayed. In the above example, three data fields -- ItemNumber, ItemName, and ItemPrice -- are extracted for display for all records in the Products table. Note that data binding can take place only in the <ItemTemplate>, not in the header or footer sections of the Repeater.

Although these simple binding expressions can work for a Repeater, it is more conventional to bind output to server controls to take advantage of styling properties of the controls. An alternative to coding the above Repeater is shown below using Label controls as display areas with output bound to the Text properties of the controls.

<asp:Repeater id="ProductsTable" DataSourceID="Products" Runat="Server">
  <ItemTemplate>
    <asp:Label Text='<%# Eval("ItemNumber") %>' Runat="Server"/>, 
    <asp:Label Text='<%# Eval("ItemName") %>' Runat="Server"/>, 
    <asp:Label Text='<%# Eval("ItemPrice") %>' Runat="Server"/><br/>
  </ItemTemplate>
</asp:Repeater>
Listing 8-2. Binding a data source to Repeater controls.

Formatting a Repeater as a Table

There can be three sections of Repeater output described within <HeaderTemplate>, <ItemTemplate>, and <FooterTemplate> sections of the control. The HeaderTemplate appears one time at the beginning of output; the ItemTemplate is repeated for as many records as there are in the bound data source; the FooterTemplate appears one time at the close of output. These three sections are ideally suited for displaying output within a table format.

Product Listing
Number Name Price Qty Amount
BU1111 Microsoft Office Professional 2003 419.99 20 8,399.8
BU2222 WordPerfect Office 12 210.25 18 3,784.5
BU3333 Project 2003 519.99 10 5,199.9
DB1111 Access 2003 194.95 15 2,924.25
DB2222 SQL Server 2000 Standard 1,989.95 10 19,899.5
DB3333 FileMaker Pro 6 275.95 8 2,207.6
DP1111 FrameMaker 7.0 799.95 10 7,999.5
DP2222 QuarkXPress 6.0 869.95 3 2,609.85
GR1111 Photoshop CS 589.95 17 10,029.15
GR2222 Illustrator CS 359.95 6 2,159.7
GR3333 Studio/MX 2004 969.95 13 12,609.35
GR4444 Flash/MX 2004 499.99 8 3,999.92
GR5555 Creative Suites Premier 1.1 1,109.99 23 25,529.77
OS1111 Windows XP Home 49.95 20 999
OS2222 Windows XP Professional 139.95 15 2,099.25
OS3333 Windows Server 2003 949.95 7 6,649.65
WB1111 HomeSite 5.0 94.95 27 2,563.65
WB2222 Dreamweaver MX 2004 379.95 8 3,039.6
WB3333 FrontPage 2003 179.95 22 3,958.9
WB4444 Visual Studio .NET Professional 749.88 7 5,249.16
Source: Products table
Figure 8-4. Using a Repeater to display a recordset in table format.
<asp:AccessDataSource id="Products" Runat="Server"
  DataFile="../Databases/eCommerce.mdb"
  SelectCommand="SELECT * FROM Products"/>
	
<asp:Repeater id="ProductsTable" DataSourceID="Products" Runat="Server">
  <HeaderTemplate>
    <table border="1" cellpadding="2" style="border-collapse:collapse">
    <tr style="background-color:#707070; color:#FFFFFF">
      <th>Number</th>
      <th>Name</th>
      <th>Price</th>
      <th>Qty</th>
      <th>Amount</th>
    </tr>
  </HeaderTemplate>
  <ItemTemplate>
    <tr>
      <td><asp:Label Text='<%# Eval("ItemNumber") %>' Runat="Server"/></td>
      <td><asp:Label Text='<%# Eval("ItemName") %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# FormatNumber(Eval("ItemPrice")) %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# Eval("ItemQuantity") %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# FormatNumber(Eval("ItemPrice") * Eval("ItemQuantity")) %>' Runat="Server"/></td>
    </tr>
  </ItemTemplate>
  <FooterTemplate>
    <tr style="background-color:#707070; color:#FFFFFF">
      <td colspan="5" style="font-size:10pt; font-style:italic">
        Source: Products table
      </td>
    </tr>
   </table>
  </FooterTemplate>
</asp:Repeater>
Listing 8-3. Binding a data source to a Repeater with Template rows.

The <HeaderTemplate> contains HTML code to define a table and describe its column headings, which are displayed once within the output. The <ItemTemplate> contains code to describe a table row that is repeated once for each record in the recordset. The <FooterTemplate> contains code for the closing table tags that appear once at the end of output.

Notice that template columns can contain output other than reports of single data field values. In this example, item amounts are calculated by multiplying the ItemPrice field times the ItemQuantity field using an in-line expression involving these bound fields. In addition, a binding expression can call a Visual Basic function to return a value for binding to the column. For example, item amounts can be calculated and displayed with the following alternative code for the amount column.

Function Get_Amount (Price As Decimal, Quantity As Decimal)

  Dim Amount As Decimal = Price * Quantity
  Return String.Format("{0:#,#.##}", Amount)
	
End Function

<td style="text-align:right">
  <asp:Label Text='<%# Get_Amount(Eval("ItemPrice"), Eval("ItemQuantity")) %>' Runat="Server"/></td>
Listing 8-4. Using a function to return a calculated value.

The ItemPrice and ItemQuantity values for a row are passed to function Get_Amount where the amount is calculated and formatted with a custom format string for return to the calling statement for display.

Other Templates

An <AlternatingItemTemplate> can be coded following the <ItemTemplate> to decribe the appearance of alternating rows of output. The AlternatingItemTemplate is a repeating template that can contain different data items from the ItemTemplate. A <SeparatorTemplate> can be coded to describe a separator line between each detail line of display.

In the following example an Alternating ItemTemplate is added to the previous Repeater to produce alternating row shadings. Also, a SeparatorTemplate writes a horizontal rule between table rows.

Product Listing
Number Name Price Qty Amount
BU1111 Microsoft Office Professional 2003 419.99 20 $8,399.80

BU2222 WordPerfect Office 12 210.25 18 $3,784.50

BU3333 Project 2003 519.99 10 $5,199.90

DB1111 Access 2003 194.95 15 $2,924.25

DB2222 SQL Server 2000 Standard 1,989.95 10 $19,899.50

DB3333 FileMaker Pro 6 275.95 8 $2,207.60

DP1111 FrameMaker 7.0 799.95 10 $7,999.50

DP2222 QuarkXPress 6.0 869.95 3 $2,609.85

GR1111 Photoshop CS 589.95 17 $10,029.15

GR2222 Illustrator CS 359.95 6 $2,159.70

GR3333 Studio/MX 2004 969.95 13 $12,609.35

GR4444 Flash/MX 2004 499.99 8 $3,999.92

GR5555 Creative Suites Premier 1.1 1,109.99 23 $25,529.77

OS1111 Windows XP Home 49.95 20 $999.00

OS2222 Windows XP Professional 139.95 15 $2,099.25

OS3333 Windows Server 2003 949.95 7 $6,649.65

WB1111 HomeSite 5.0 94.95 27 $2,563.65

WB2222 Dreamweaver MX 2004 379.95 8 $3,039.60

WB3333 FrontPage 2003 179.95 22 $3,958.90

WB4444 Visual Studio .NET Professional 749.88 7 $5,249.16
Figure 8-5. Using a Repeater with an AlternatingItemTemplate and SeparatorTemplate.
<asp:AccessDataSource id="Products" Runat="Server"
  DataFile="../Databases/eCommerce.mdb"
  SelectCommand="SELECT * FROM Products"/>
	
<asp:Repeater id="ProductsTable" DataSourceID="Products" Runat="Server">
  <HeaderTemplate>
    <table border="0" cellpadding="2" style="background-color:#F0F0F0; border-collapse:collapse">
    <caption style="font-size:14pt; font-weight:bold">Product Listing</caption>
    <tr style="background-color:#707070; color:#FFFFFF">
      <th>Number</th>
      <th>Name</th>
      <th>Price</th>
      <th>Qty</th>
      <th>Amount</th>
    </tr>
  </HeaderTemplate>
  <ItemTemplate>
    <tr>
      <td><asp:Label Text='<%# Eval("ItemNumber") %>' Runat="Server"/></td>
      <td><asp:Label Text='<%# Eval("ItemName") %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# String.Format("{0:N}", Eval("ItemPrice")) %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# String.Format("{0:D}", Eval("ItemQuantity")) %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# String.Format("{0:C}", Eval("ItemPrice") * Eval("ItemQuantity")) %>' Runat="Server"/></td>
    </tr>
  </ItemTemplate>
  <AlternatingItemTemplate>
    <tr style="background-color:#A0A0A0; color:#FFFFFF">
      <td><asp:Label Text='<%# Eval("ItemNumber") %>' Runat="Server"/></td>
      <td><asp:Label Text='<%# Eval("ItemName") %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# String.Format("{0:N}", Eval("ItemPrice")) %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# String.Format("{0:D}", Eval("ItemQuantity")) %>' Runat="Server"/></td>
      <td style="text-align:right">
        <asp:Label Text='<%# String.Format("{0:C}", Eval("ItemPrice") * Eval("ItemQuantity")) %>' Runat="Server"/></td>
    </tr>
  </AlternatingItemTemplate>
  <SeparatorTemplate>
    <tr>
      <td colspan="5"><hr/></td>
    </tr>
  </SeparatorTemplate>
  <FooterTemplate>
    </table>
  </FooterTemplate>
</asp:Repeater>
Listing 8-5. Coding a Repeater with various template rows.

As you can see, coding a Repeater makes use of HTML to format its output. Therefore, you need to be familiar with this language and with CSS style settings to produce displays.

Using a ContentPager with a Repeater

When using a Repeater with a large database, the output display can become too lengthy to fit comfortably on a page. There is a need for paging the output. Although a Repeater does not have a built-in paging feature like a GridView, DetailsView, or FormView, you still can display subsets of records in a Repeater with an <asp:ContentPager> control as shown in the following example.

Number Type Supplier Name Description Price Qty. Sale Picture
BU1111 Business Office Microsoft Microsoft Office Professional 2003
Microsoft Office Professional Edition 2003 can help you and your organization communicate information with immediacy and impact. New and familiar programs and improved functionality help you build powerful connections between people, information, and business processes.
419.99 20
BU2222 Business Office Corel WordPerfect Office 12
Powerful word processing, spreadsheet, and presentation applications. Compatible with Microsoft Office, PDF, HTML, XML, and more. Intuitive Publish to PDF feature; no need for additional PDF software. Maximizes efficiency; versatile and easy to use.
210.25 18
BU3333 Business Office Microsoft Project 2003
Organize your work more effectively with new scheduling tools -- Track schedule and resource changes to your project plans quickly. New display options lets you show individuals the project information they need to review. Increase your impact at work and create better presentations to print compelling and succinct copies of schedules and goals. Move information easily between Project 2003 and other Microsoft Office programs, such as Excel. Updated interface and new templates available for downloading, make this version of Project the most user-friendly ever!
519.99 10
DB1111 Database Microsoft Access 2003
Supports a variety of data formats, including Extensible Markup Language ( XML ), OLE, Open Database Connectivity ( ODBC ), and Microsoft Windows SharePoint Services. Access data from multiple databases in forms, reports, and data access pages, linking tables from other Access databases, Microsoft Excel spreadsheets, ODBC data sources, Microsoft SQL Server databases & other sources. Stored Procedure Designer creates & modifies procedures stored in SQL Server, without requiring you to learn Transact-SQL. Quickly find tables, queries, forms or reports that depend on a particular database object. Update properties automatically files to previous versions of Access and directly integrate data with Microsoft SQL Server.
194.95 15
DB2222 Database Microsoft SQL Server 2000 Standard
10 client. XML stored procedure support. XML update grams. Large memory and SMP support. Integrated data mining, full text search, English (natural language) Query. Indexed (materialized) views and integrated visual studio graphical tools.
1,989.95 10
1 2 3 4 
Figure 8-6. Paging records with a Repeater control.

Any server control with multiple items associated with it can be paged by associating it with an <asp:ContentPager> control. The following general format shows common property settings for this control.

<asp:ContentPager id="id" Runat="Server"
  ControlToPaginate="controlID"
  ItemsPerPage="n"
  Mode="NextPrevious|Numeric|NextPreviousFirstLast|NumericFirstLast"
  PageButtonCount="n"
    ButtonStyle-property="value"...
    Style="CSS style settings..."
/>
Figure 8-7. General format for <asp:ContentPager> control.

A ContentPager is associated with a display control such as a Repeater by coding the latter's id as the ControlToPaginate property value. The number of lines of output to display per page is given by the ItemsPerPage property, and the number of buttons to display at a time is given by the PageButtonCount property. The type of paging buttons to display is set with the Mode property.

The following table shows additional properties that can be applied to the control. These properties are similar to those used for the built-in pager for the GridView, DetailsView, and FormView controls. You can, for instance, choose to change the default text of paging buttons or substitute graphic images.

FirstImageUrl="url" Sets the image to be used for first-page button.
FirstPageText="string" Sets the text to be used for first-page button.
LastImageUrl="url" Sets the image to be used for last-page button.
LastPageText="string" Sets the text to be used for last-page button.
NextImageUrl="url" Sets the image to be used for next-page button.
NextPageText="string" Sets the text to be used for next-page button.
PreviousImageUrl="url" Sets the image to be used for previous-page button.
PreviousPageText="string" Sets the text to be used for previous-page button.
Figure 8-8. ContentPager settings.

Here is an important point. The ContentPager must be coded following the control to which it is connected. This is shown in the code listing below for the above Repeater. An alternative is to place the control inside the Repeater, say, inside the FooterTemplate, following the paged lines being displayed.

<asp:AccessDataSource id="ProductsSource" Runat="Server"
  DataFile="../Databases/eCommerce.mdb"
  SelectCommand = "SELECT * FROM Products ORDER BY ItemNumber"/>

<asp:Repeater id="RepeaterDisplay" Runat="Server"
  DataSourceID="ProductsSource">

  <HeaderTemplate>
    <table id="RepeaterTable" border="1" style="border-collapse:collapse">
    <tr style="background-color:#990000; color:#FFFFFF">
      <th>Number</th>
      <th>Type</th>
      <th>Supplier</th>
      <th>Name</th>
      <th>Description</th>
      <th>Price</th>
      <th>Qty.</th>
      <th>Sale</th>
      <th>Picture</th>
    </tr>
  </HeaderTemplate>

  <ItemTemplate>
    <tr style="vertical-align:top">
      <td style="width:50px; text-align:center">
        <asp:Label Text='<%# Eval("ItemNumber") %>' Runat="Server"/></td>
      <td style="width:90px">
        <asp:Label Text='<%# Eval("ItemType") %>' Runat="Server"/></td>		
      <td style="width:90px">
        <asp:Label Text='<%# Eval("ItemSupplier") %>' Runat="Server"/></td>		
      <td style="width:90px">
        <asp:Label Text='<%# Eval("ItemName") %>' Runat="Server"/></td>	
      <td><asp:Panel ScrollBars="Auto" Width="220" Height="60" Runat="Server">
            <asp:Label Font-Size="9" Style="line-height:10pt" Runat="Server"
              Text='<%# Eval("ItemDescription") %>'/><br/>
          </asp:Panel></td>	
      <td style="width:50px; text-align:right">
         <asp:Label Text='<%# FormatNumber(Eval("ItemPrice")) %>' Runat="Server"/></td>		
      <td style="width:30px; text-align:right">
        <asp:Label Text='<%# Eval("ItemQuantity") %>' Runat="Server"/></td>		
      <td style="text-align:center">
        <asp:CheckBox Checked='<%# Eval("ItemSale") %>' Runat="Server"/></td>
      <td>
        <asp:Image Width="50px" Runat="Server"
          ImageUrl='<%# "../Pictures/" & Eval("ItemNumber")& ".jpg"%>'/></td>
    </tr>
  </ItemTemplate>

  <FooterTemplate>
    </table>
  </FooterTemplate>

</asp:Repeater>

<asp:ContentPager id="Pager" Runat="Server"
  ControlToPaginate="RepeaterDisplay"
  ItemsPerPage="5"
  Mode="Numeric"/>
Listing 8-6. Coding a Repeater with a ContentPager.

The <asp:Repeater> control provides great flexibility in formatting output from a bound data source. Virtually any HTML tags and server controls can be added to the templates to arrange and style the data items. You will probably favor this control if you prefer, or if you don't mind, coding HTML to produce your output. A Repeater does not provide automatic sorting as do the GridView, DetailsView, and FormView controls. This feature must be scripted. Sorting records for a Repeater is discussed under the topic "Displaying Sorted Records."