|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
How to: Add a Repeater Control to a Web Forms Page
TheWeb server control is a container control that allows you to create custom lists out of any data that is available to the page. Adding a Repeater Web server control to a page requires several steps. The following procedure describes the minimum that you must do to create a working Repeater control.
To add a Repeater Web server control to an ASP.NET page
Add a data source control to the page, such as aor control. For details, see .
Configure the data source control to perform a query.
If you are using a SqlDataSource orcontrol, specify connection information and an SQL query for the property. If you are using a ObjectDataSource control, configure its property.
<asp:Repeater>element to the page. For syntax, see .
Set the Repeater control'sproperty to the ID of the data source control.
<ItemTemplate>element into the page as a child of the Repeater control. For syntax, see .
The Repeater control must contain at least anthat in turn contains data-bound controls in order for the control to render at run time.
For background information about using templates, see.
Add HTML markup and Web server controls or HTML server controls to the ItemTemplate.
Bind the child controls to data from the query using the Eval data-binding function, as shown in the following example.
<ItemTemplate> <tr> <td bgcolor="#CCFFCC"> <asp:Label runat="server" ID="Label1" Text='<%# Eval("CategoryName") %>' /> </td> <td bgcolor="#CCFFCC"> <asp:Label runat="server" ID="Label2" Text='<%# Eval("Description") %>' /> </td> </tr> </ItemTemplate>
For information on data-binding functions, see.
Optionally, define an, , , or .
The following example shows how to use a Repeater control to display data in an HTML table. The table element begins in the HeaderTemplate and ends in the FooterTemplate. Within the body of the Repeater control, table cells are used to display columns from the data source. The AlternatingItemTemplate element is identical to the ItemTemplate item except that the background color for the table cells is different to create a banded effect.
The example requires a connection string that can be used to connect to the sample Northwind database in Microsoft SQL Server. The connection string must be defined in the <connectionStrings> element of the application's Web.config file. The <connectionStrings> section might look like the following example:
<configuration> <connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;" /> </connectionStrings> <system.web> <!-- Other configuration settings -->s </system.web> </configuration>