The ASP.NET Repeater Web Server Control

by John Peterson


Introduction

If you've been using ASP.NET for any length of time then you've almost certainly utilized the DataGrid Server Control. And I'm sure a good portion of you have probably played with the DataList as well... after all, not all of our tables can only have one item per row. But what about that other data web control? I've got a friend who probably will kill me for using this analogy, but it's sort of like the three tenors... there's Pavarotti, Domingo, and that other guy (his name is actually Carreras, but you get my point). Well the other guy in this case is a great little control called the Repeater. While the repeater may not be as well known as or have all the bells and whistles of the other controls, it does have something that neither of the other two has: flexibility.

Flexibility

Why do I say the Repeater is the most flexible of the three data web controls? Because it's the only one that doesn't add a bunch of its own HTML to your data. If you want just the plain data spit out on the page you can easily get it. Try and do that with either of the other two and you'll quickly find that you're simply out of luck. If you want some sort of fancy custom HTML, that's no problem either.

The reason the Repeater is more flexible then the others, is that both the DataGrid and the DataList are based upon the HTML table element, and while there's nothing wrong with that, it can somewhat limit your (or your designer's) creativity when it comes to displaying your data. The Repeater is not limited to rendering a table. You can use it to output any type of formatting you choose using as little or as much of your own custom HTML as you please.

The Downside

Unfortunately, all this flexibility does come at a cost. The Repeater does not have the built in selection or editing support of the DataGrid and DataList. You can write your own, but it will add to the amount of code needed for your application. If you don't need the additional abilities, then you've lucked out and gained the flexibility of being able to use your own HTML without having to write this extra code.

The Code

To keep things brief... I'm only including the actual Repeater controls in the code listing below. The code I use to create the DataTable and the code that does the actual databinding are contained in this article's download.

I've included four repeaters on the page, and they all use the same set of data. The first simply displays the data in a comma-delimited format with one record per line. The second repeater uses the data to build an HTML unordered list of links with each record representing one list item formatted to produce an HTML link. The third is very similar to the second with an AlternatingItemTemplate and SeparatorTemplate thrown in for illustration. The last repeater uses the image data to build an HTML img tag to show images instead of text for the links. In this case I use the site name as the alt attribute of the img tag.


<asp:Repeater id="myRepeaterPlain" runat="server">
  <ItemTemplate>
    <%# DataBinder.Eval(Container.DataItem, "Id") %>,
    <%# DataBinder.Eval(Container.DataItem, "Name") %>,
    <%# DataBinder.Eval(Container.DataItem, "URL") %>,
    <%# DataBinder.Eval(Container.DataItem, "Image") %>
    <br />
  </ItemTemplate>
</asp:Repeater>

<hr />

<asp:Repeater id="myRepeaterUL" runat="server">
  <HeaderTemplate>
    <ul>
  </HeaderTemplate>
  <ItemTemplate>
    <li><a href="<%# DataBinder.Eval(Container.DataItem, "URL") %>">
      <%# DataBinder.Eval(Container.DataItem, "Name") %></a></li>
  </ItemTemplate>
  <FooterTemplate>
    </ul>
  </FooterTemplate>
</asp:Repeater>

<hr />

<asp:Repeater id="myRepeaterAltSep" runat="server">
  <HeaderTemplate>
    <p><strong>Selected ASP Sites:</strong><br />
  </HeaderTemplate>
  <ItemTemplate>
    <a href="<%# DataBinder.Eval(Container.DataItem, "URL") %>">
      <%# DataBinder.Eval(Container.DataItem, "Name") %></a><br />
  </ItemTemplate>
  <AlternatingItemTemplate>
    <font style="background-color: #CCCCFF">
    <a href="<%# DataBinder.Eval(Container.DataItem, "URL") %>">
      <%# DataBinder.Eval(Container.DataItem, "Name") %></a><br />
    </font>
  </AlternatingItemTemplate>
  <SeparatorTemplate>
    -----------------------<br />
  </SeparatorTemplate>
  <FooterTemplate>
    <strong>End Selected ASP Sites</strong></p>
  </FooterTemplate>
</asp:Repeater>

<hr />

<asp:Repeater id="myRepeaterImage" runat="server">
  <ItemTemplate>
    <a href="<%# DataBinder.Eval(Container.DataItem, "URL") %>">
      <img src="<%# DataBinder.Eval(Container.DataItem, "Image") %>"
      border="0"
      alt="<%# DataBinder.Eval(Container.DataItem, "Name") %>"/></a>
  </ItemTemplate>
</asp:Repeater>

Here's the result. Now remember that all 4 are built using the exact same data:


Figure 1: Repeater Output Screen Capture

Download

You can download the complete code below (which naturally includes all the code listed above).



About the Author

From ASP101

Articles originally posted on ASP101.com

Downloads

Comments

  • ZjPrgp mA US fvl niPy BG

    Posted by qnFRKBVxtj on 06/21/2013 10:00am

    buy tramadol online tramadol hcl schedule - buy tramadol with mastercard

    Reply
  • where you can procure the cheapest clarisonic mia

    Posted by iouwanzi on 06/06/2013 07:53pm

    [url=http://www.miaclarisonicaustralia.org/]clarisonic mia 2[/url] Avec concernant la saison de Noël, j’ai couru à travers une idée de cadeau vraiment attractif, votre package de Collection de nuit. un nouvel ensemble de boîte très exquis option limitée en place qui comprend également tous les flambant neuf G Platinum intemporelle GHD Styler haute définition, matériel résistant à la chaleur, seulement deux caractéristiques montre les cheveux bouclés, un nouveau miroir de belle main baroque, un séchoir de cheveux bouclés nouvelles d’acquérir voyage autour ultra-compact, ainsi qu’une belle organisation. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia 2[/url] Vous venez ou peut-être pas ?Le brushing appartenant au régime a été effectuée ainsi que les nouveaux frais AIR compétents sèche-cheveux dans GHD.Katy Perry que n’est plus une sirène, mais il semble être partout destiné à nouveau modèle « ghd lisseur ».Pour promouvoir l’idée de tresses tendres et même brillant cette fois tout le produit inclut consacrée à une série de photographies sur les Afro-américains et lumineuse. Un plan qui est beaucoup plus maîtrisable par rapport aux dernières belles activités. Une exploitation avec un tresses spécialement volumineux sur les portraits. [url=http://www.miaclarisonicaustralia.org/]clarisonic australia[/url] Modèle d’organisation ghd fer des prix, qui sont eux-mêmes trouvés sur le marché, maintenant il ya beaucoup de gens qui ont pu être mieux. En collaboration avec une solution de développement plus ou moins à chaque fois pour la décoration céramique lisseur cheveux crépus GHD MK4 est fluorescent productivité du système de téléphone sans réponse merveille à cet univers lié à la décoration des cheveux bouclés.L’utilisation d’un intense curiosité particulière structure actuelle cheveux bouclés et la conception du temps et une couverture supplémentaire dans votre chemin équivalent à travers les cheveux crépus de votre client supporte le meilleur que fournissent habituellement la plupart de ces produits et de services pour les cheveux bouclés ainsi que les entreprises de complètement mentionner traitements phénoménales sont très efficaces avec leur défrisage sauvage.

    Reply
  • How do I embed a different image for each repeated item

    Posted by DJ on 04/10/2013 02:47pm

    I have been completely unsuccessful at tying an image to each repeated item in my repeater. I'm using the repeater as a sort of blog, and each posting in the repeater should pull a different image out of the ~/images folder. Maybe the first one has a coffee cup, and the next one a hammer, etc. It would be even better if I could have some images float left and the others float right with the text wrapping around them. No joy so far. Any ideas? Is this just a pipe dream?

    Reply
  • Sotware Developer

    Posted by Dave on 08/07/2012 11:32pm

    This was very helpfull for the template information. I have tried other sources and this one actually gave me the info I needed to display data in my repeater. Thank you very much for posting this information. Dave

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Businesses are moving more and more of their customer transactions to the web. Security is understandably a top concern as online transactions increase, so it is important to make sure your electronic signature provider meets the highest security standards. That means more than simply passing a security audit or obtaining a certification. This white paper provides recommendations for taking a broader view of e-signature security, and answers key questions that help identify the security requirements against …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds