Repeater
With the asp Repeater
control, we can bind a DataSource
and display it on a web page. With ItemTemplate
we can specify how each item is displayed.
We must use code-behind in Web Forms to set up the Repeater
. We use a List
of Strings as the DataSource
, and then call DataBind()
.
Here we see the Repeater
markup in the ASPX page. We specify the ID of the Repeater
as rep1, and this is accessed in the C# file.
ItemTemplate
. We add an internal Label control, which has the "runat server" attribute set.Repeater
to the Container.DataItem
.Container.DataItem
in this project gives us the string
in the List
that is the DataSource
.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Repeater id="rep1" runat="server"> <ItemTemplate> <asp:Label runat="server" Text="<%# Container.DataItem %>"></asp:Label> </ItemTemplate> </asp:Repeater> </div> </form> </body> </html>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // The list will be used as a DataSource for the repeater. var items = new List<string>(); items.Add("Bird "); items.Add("Cat "); items.Add("Dog "); // Set DataSource and then call DataBind. rep1.DataSource = items; rep1.DataBind(); } }<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title> </title></head> <body> <form method="post" action="./Default.aspx" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="..." /> </div> <div> <span>Bird </span> <span>Cat </span> <span>Dog </span> </div> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATEGENERATOR" id="..." value="CA0B0334" /> </div></form> <!-- Visual Studio Browser Link --> <script type="application/json" id="__browserLink_initializationData"> {"appName": "Chrome","requestId": "bcd1d084c851454690b699749f67022a"} </script> <script type="text/javascript" src="..." async="async"></script> <!-- End Browser Link --> </body> </html>
If you run this website in Visual Studio, you will see that the Repeater
is rendered as 3 span tags in the HTML. These are from the List
of Strings.
List
of Strings and use it as the DataSource
of a Repeater
, which renders the data to the HTML page.To add the Repeater
, open the file in Visual Studio, and start typing "repeater." A snippet will be available—press tab to insert the entire Repeater
.
We use the Repeater
alongside the ItemTemplate
, Label in ASPX markup. And we used DataSource
and DataBind
in the code-behind file.