Making Use of the Repeater Web Server Control

If you had a chance to read my two articles detailing the use of the DataGrid web server control (Return of the DataGrid and Behold the Power of the DataGrid), then no doubt you're excited to see how great .Net is for Rapid Application Development. However, you may have found the DataGrid a little inflexible for your needs. Perhaps you wanted to alter the output, and don't like being constrained to a <table>. Well, if you can do without the fancy editing and sorting functionality, then the Repeater Control is just the Control for your needs.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 18
June 28, 2004
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Introduction

What exactly is a Repeater Web Server Control, and what does it do? To over-simplify and encapsulate the answers to both questions at once, a Repeater is a mechanism for repeating data. Hence the name. If you'd like a little more detail (of course you do, otherwise you wouldn't be the type to be researching on ASPFree!), a Repeater is a template-controlled data-bound list.

Now when I say template-controlled, what I mean is that you have to specify what data you wish to repeat, and in what layout. But beyond that there are four optional areas of the Repeater that can be controlled through separate templates.

The Repeater also offers the option of embedding other controls within itself, and then bubbling up and capturing events from those controls.

These capabilities just mentioned combine to offer what is a very flexible way to handle something such as a shopping cart application. And that is precisely what this article will show you how to do, step by step.

Get the Data

Let's start off by assuming that you've got all of product information stored in a database. This article will not go into creating or populating a database, but it is assumed that you've mastered the basics (by basic, I mean Microsoft Access). I will assume you have the following fields in a 'products' table, in an Access database:

id description manufacturer color price imgPath

This is by no means a normalized database we're dealing with here, nor does it need to be for the sake of teaching how to use a Repeater. Most of the fields are self-descriptive, however the 'imgPath' will be pointing to the relative path of a picture of the product. This is not absolutely necessary, but it's a good idea, and it's also a nice way to show off the flexibility of the Repeater, as you will see.

This article is not a tutorial on data retrieval either. I will though, include the necessary code to do the data extraction from the database, with a small explanation of what's going on. We will need a subroutine called doBinding(), which will do the data retrieval, and the binding.

Sub doBinding()

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _

"Ole DB Services=-4; " & _

"Data Source=C:\Inetpub\wwwroot\store.mdb"

Dim dbConnection As OleDbConnection = New OleDbConnection(strConn)


Dim strSQL As String = "SELECT * FROM products"


Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter( strSQL, strConn)


Dim dataSet As DataSet = New DataSet

dataAdapter.Fill(dataSet)

We've done the all the needed work to extract the data into a dataset, and all that's left is to tell the repeater to use that data. Do that by 'binding', or attaching, it to the dataset. We'll assume the name of the repeater will be prodRepeater:

prodRepeater.DataSource = dataSet

prodRepeater.DataBind()

End Sub

Now add in the code responsible for calling this subroutine and populating the repeater the first time the page is loaded:

sub page_load( source as Object, e as EventArgs )

if not isPostBack then

doBinding()

end if

end sub

Can You Repeat That Please?

Now that we have the data and the repeater is bound to it, you're going to need to know how to actually make use of it. I mentioned that there are five different template areas, and I'll list them now:

  1. HeaderTemplate – The header (for example, you would place your starting '<table>' HTML code here.
  2. ItemTemplate – which DataItem fields are displayed, and how.
  3. AlternatingItemTemplate – How are the odd items displayed? By odd I mean odd-indexed, not the strange items (I don't think .Net is smart enough to pick out which items are strange anyways). This would be useful if you want to perhaps change the background color of every other item, which helps to visually distinguish them.
  4. SeparatorTemplate – Perhaps you want to use something to separate the items, such as a line ('<hr />').
  5. FooterTemplate – Finally, the footer. If you placed <table> in your header, it would be wise to put </table> here.

Of the five templates, the only one that .Net actually requires you to provide is the ItemTemplate. Once it knows which items to display, it will happily do about its business not even caring that you omit the others. You can even configure the header and leave out the footer without encountering any errors, though I'm not sure I understand why you would want to...

This is how you could use the templates:

<asp:Repeater id="prodRepeater" runat="server">

<HeaderTemplate>

<table cellpadding="3" border="0" cellspacing="0">

</HeaderTemplate>

<ItemTemplate>

<tr>

<td style="font-family:verdana;font-size: 11px;">

Desc: <%# Container.DataItem("description") %><br />

Mfg: <%# Container.DataItem("manufacturer") %><br />

Color: <%# Container.DataItem("color") %><br />

Cost: <%# FormatCurrency( Container.DataItem("price")) %>

</td>

<td style="font-family:verdana;font-size: 11px;">Picture: <br />

<img src="<%# Container.DataItem("imgPath") %>" />

</td>

</tr>

</ItemTemplate>

<AlternatingItemTemplate>

<tr style="background-color:#666666;color:#ffffff;">

<td style="font-family:verdana;font-size: 11px;">

Item: <%# Container.DataItem("description") %><br />

Mfg: <%# Container.DataItem("manufacturer") %><br />

Color: <%# Container.DataItem("color") %><br />

Cost: <%# FormatCurrency( Container.DataItem("price")) %>

</td>

<td style="font-family:verdana;font-size: 11px;">Picture: <br />

<img src="<%# Container.DataItem("imgPath") %>" />

</td>

</tr>

</AlternatingItemTemplate>

<SeparatorTemplate>

<tr><td style="height:2px;background-color:#333333" colspan="2"></td></tr>

</SeparatorTemplate>

<FooterTemplate>

</table>

</FooterTemplate>

</asp:Repeater>

This would give you a nice little table with every other row colored dark gray. Of course, having the SeparatorTemplate insert a two pixel dark gray row in between each is a little redundant, but I thought it appropriate to use for the sake of the tutorial. Now let's get into event bubbling, which would be absolutely vital in an e-commerce situation.

Ooooh, Bubbles!

Suppose you've decided that along with your nicely styled repetition of your inventory, it would be somewhat beneficial to your business for people to actually be able to purchase one or more of the items. A nice way to do that is stick a little button unambiguously labeled 'buy'. When you click 'buy', you want a subroutine that takes the ID of the item you want to buy, and takes you to the next step of credit card processing and such.

I won't bother with the next step here, but I will show you how to embed a button control in the Repeater, and how to configure the button (child) to make the Repeater (parent) aware of its events. This is called bubbling. Think of bubbles starting at the bottom of a boiling pot, and rising to the surface to pop. That's essentially what's happening; the events/bubbles start at the bottom - the child - and rise to the top – the parent – to be handled.

To do this, first we add the code to the container, the Repeater, to capture the events. Our repeater will now look like this:

<asp:Repeater id="prodRepeater" runat="server" onItemCommand="getItem">

Then, we add the child control, the button to the item template, and the alternating item template if you are using one. It would look like this:

<asp:button runat="server" text="buy" CommandArgument='<%# Container.DataItem("id") %>' />

We hide the id of the item in the CommandArgument member of the button, which we will pick up later. Once a user clicks 'buy', this raises an event, which is bubbled up to the repeater, which will hand it off to the following getItem() subroutine:

Sub getItem( s as object, e as RepeaterCommandEventArgs )

'response.write( "id: " + e.CommandSource.CommandArgument )

Dim id as String = e.CommandSource.CommandArgument.ToString()

Response.redirect( "buy.aspx?intID=" + id )

End Sub

As you can see, this subroutine picks up the value from the button control though the CommandArgument member. We could do lots of things with this now, but for simplicity's sake I have just chosen to hand it off to another page ('buy.aspx') with the ID of the desired product.

Conclusion

As you will see, the repeater is a highly flexible but easy to use control. It doesn't have all the bells and whistles of the DataGrid, but in a situation where they aren't needed, it's extremely fast to employ the Repeater. To end it off I'll leave you with the full code of the page:

<%@ Page Language="VB" debug="true" %>

<%@ import Namespace="System.Data" %>

<%@ import Namespace="System.Data.OleDb" %>

<script runat="server">


sub page_load( source as Object, e as EventArgs )

if not isPostBack then

doBinding()

end if

end sub


Sub doBinding()

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _

"Ole DB Services=-4; " & _

"Data Source=C:\Inetpub\new\test.mdb"


Dim dbConnection As OleDbConnection = New OleDbConnection(strConn)


Dim strSQL As String = "SELECT * FROM products"


Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter( strSQL, strConn)


Dim dataSet As DataSet = New DataSet

dataAdapter.Fill(dataSet)


prodRepeater.DataSource = dataSet

prodRepeater.DataBind()

End Sub


Sub getItem( s as object, e as RepeaterCommandEventArgs )

'response.write( "id: " + e.CommandSource.CommandArgument )

Dim id as String = e.CommandSource.CommandArgument.ToString()

Response.redirect( "buy.aspx?intID=" + id )


End Sub


</script>

<html>

<head>

</head>

<body>

<form runat="server">

<asp:Repeater id="prodRepeater" runat="server" onItemCommand="getItem">

<HeaderTemplate>

<table cellpadding="3" border="0" cellspacing="0">

</HeaderTemplate>

<ItemTemplate>

<tr>

<td style="font-family:verdana;font-size: 11px;">

Desc: <%# Container.DataItem("description") %><br />

Mfg: <%# Container.DataItem("manufacturer") %><br />

Color: <%# Container.DataItem("color") %><br />

Cost: <%# FormatCurrency( Container.DataItem("price")) %>

</td>

<td style="font-family:verdana;font-size: 11px;">Picture: <br />

<img src="<%# Container.DataItem("imgPath") %>" /><br />

<asp:button runat="server" text="buy" CommandArgument='<%# Container.DataItem("id") %>' />

</td>

</tr>

</ItemTemplate>

<AlternatingItemTemplate>

<tr style="background-color:#666666;color:#ffffff;">

<td style="font-family:verdana;font-size: 11px;">

Item: <%# Container.DataItem("description") %><br />

Mfg: <%# Container.DataItem("manufacturer") %><br />

Color: <%# Container.DataItem("color") %><br />

Cost: <%# FormatCurrency( Container.DataItem("price")) %>

</td>

<td style="font-family:verdana;font-size: 11px;">Picture: <br />

<img src="<%# Container.DataItem("imgPath") %>" /><br />

<asp:button runat="server" text="buy" CommandArgument='<%# Container.DataItem("id") %>' />

</td>

</tr>

</AlternatingItemTemplate>

<SeparatorTemplate>

<tr><td style="height:2px;background-color:#333333" colspan="2"></td></tr>

</SeparatorTemplate>

<FooterTemplate>

</table>

</FooterTemplate>

</asp:Repeater>

</form>

</body>

</html>

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials