Deciding When to Use the DataGrid, DataList or Repeater
Summary: Learn about ASP.NET's three controls for displaying data: the DataGrid, the DataList, and the Repeater. Each of these controls has unique traits and associated advantages and disadvantages. When creating an ASP.NET application that displays data, it is important to choose the right control for the job. As we will see in this article, choosing whether to use the DataGrid, DataList, or Repeater is a tradeoff between three factors: usability, development time, and performance. (12 printed pages)
Web development has come a long way since simple script-based Web programming technologies like Microsoft® Active Server Pages (ASP). With Microsoft ASP.NET, a lot of the tedious, repetitious coding chores that were commonplace with classic ASP are now a thing of the past. For example, as all one-time classic ASP developers know, displaying data in a classic ASP Web page required the following pseudocode:
Create connection to the database Populate an ADO Recordset with a SQL query Display any header HTML needed For Each Record in the Recordset Print out the Recordset field(s) and associated HTML Move to the next record Next Display any footer HTML needed
For example, to display the contents of a Recordset in an HTML
<table>, a developer would have to emit the HTML markup for the
<table> tag, then loop through each record in the Recordset, emitting a single
<tr> tag per loop, and a number of
<td> tags along with the values of the Recordset fields she was interested in displaying. Finally, after the loop, the developer would need to emit the closing
This approach required by classic ASP has one major disadvantages: it tightly integrates the HTML content with the ASP Web page's source code. By not separating the code and HTML content, it is exponentially more difficult to make changes to the HTML content, especially for graphic artists or Web designers who might not be savvy with programming technologies. Furthermore, this integration of code and HTML content requires a relatively large amount of code, since code is needed for both retrieving the database results and emitting its contents.
Fortunately, ASP.NET offers three controls that make displaying data in an ASP.NET Web page overwhelmingly simpler than the iterative approach required in classic ASP. These three controls, which I will refer to henceforth as the data Web controls, are the DataGrid, DataList and Repeater. Chances are, if you've already developed ASP.NET Web pages you have already had some experience with at least one of these three controls. Most commonly, developers start learning about the DataGrid, due to the ease with which it can be used and its ability to allow for sorting, paging and editing of its data. However, the DataGrid is not always the best choice for a control when displaying data in an ASP.NET Web page.
In this article, we will examine the unique traits of each of the data Web controls. These traits give each data Web control a number of advantages and disadvantages. Since each data Web control has some disadvantage, there is no "perfect" control for any job. In deciding what control to use you must weigh the benefits and demerits of each of the three data Web controls and decide what the best control to use is.
To aid in our comparison, when examining each of the data Web controls we'll focus on three metrics: usability (from the perspective of the Web visitor), development time and performance. We'll start with a quick look at the similarities among the three data Web controls. Next, we'll delve into an examination of the DataGrid, and then move onto the DataList, and finally look at the Repeater. With each control we'll look at the controls' features and discuss how its feature set affects these metrics.
Before we examine the differences among the data Web controls that make them unique from one another, let's first look at their similarities. The most general similarity is that, from a very high-level point of view, the DataGrid, DataList and Repeater were all designed to do roughly the same thing: display data. Another similarity is the code needed to bind data to the data Web controls. Specifically, only two lines of code are needed:
dataWebControlID.DataSource = someDataSource dataWebControlID.DataBind()
someDataSource object assigned to the data Web control's
DataSource property will be a DataSet, SqlDataReader, OleDbDataReader or a collection (such as an Array, an ArrayList or some other class in the
System.Collections namespace). However, any object that implements the IEnumerable interface can be bound to a data Web control.
DataBind() method enumerates the records of the specified
DataSource. For each record in the
DataSource, an item is created and appended to the data Web control's
Items collection. Each item in a data Web control is an instance of a class. The specific class used for each of the control's items depends on the data Web control. For example, each item in the DataGrid is an instance of the
DataGridItem class, whereas each item in a Repeater is an instance of the
Each data Web control uses a different class for each of its items because it is how these items are rendered that determines the HTML markup generated by the data Web control. For example, the DataGridItem class is derived from the
TableRow class, meaning that each
DataGridItem renders, more or less, as a table row. This makes sense since the DataGrid is designed to display data in a tabular format within an HTML
<table> tag, where each item is rendered as a single row in an HTML
<table>. The Repeater, on the other hand, is designed to allow for complete customization of its output. Therefore, it's not surprising that the RepeaterItem class is not derived from the
Another similarity among the data Web controls is that each control is capable of using templates to provide a highly customizable output. The DataList and Repeater controls must use templates to specify their content, whereas the DataGrid can optionally use a template for a particular column via the TemplateColumn column type (We'll discuss the various DataGrid column types in the next section, "Examining the DataGrid Web Control.").
One final comparison worth noting is that both the DataGrid and DataList controls are derived from the
WebControl class, while the Repeater control is derived from the
Control class. The
WebControl class contains a number of aesthetic properties, such as
BorderStyle and so on. This means that with the DataGrid and DataList you can specify stylistic settings through the properties it inherits from the
WebControl class. The Repeater, however, does not have any such stylistic properties. As we'll discuss in the "Digging Into the Repeater" section, any visual settings to the Repeater's output must be specified in the Repeater's templates.
Among the three data Web controls, the DataGrid Web control is by far the most versatile in its features, but is the least flexible when it comes to customizing the actual HTML markup generated by the control. This inflexibility in the rendered HTML markup is due to the fact that the DataGrid is designed to display data in a tabular format using an HTML
<table>. Therefore, for each record being bound to the DataGrid, a single table row (
<tr>) is created, and for each field in the record that is to be displayed, a single table column (
<td>) is created.
The DataGrid comes packaged with a number of features that can greatly increase the usability of the data being displayed. For example, by setting the DataGrid's
AllowSorting property to True and adding just a bit of source code, developers can turn an ordinary DataGrid into one whose data can be sorted by the end user. Additionally, with just a bit more work, a developer can enhance the DataGrid to allow for data pagination, or inline editing of the data. These features clearly bolster the usability of the DataGrid.
In addition to its high marks in the usability field, the DataGrid also offers short development time. To get started displaying data on an ASP.NET Web page using a DataGrid, one only needs to add a DataGrid to the Web page and write two lines of code needed: the first to bind the data to the DataGrid's
DataSource, and the second to call the DataGrid's
DataBind() method. Clearly, as the number of features added to the DataGrid increases, so does the development time, but compared this development time to the other data Web controls. Imagine that you wanted to allow sorting of the data displayed by the Repeater. Adding such functionality is definitely possible, but would require significantly more time and energy than to do the same with the DataGrid.
Despite the DataGrid's impressive usability and development time ratings, there are two disadvantages inherent with this control. First, as touched upon earlier, the DataGrid is very limited in the customization of the rendered HTML markup. Yes, you can customize the fonts, colors, and borders of the DataGrid's various rows and columns, but the fact still remains that when the DataGrid displays your data it will be in an HTML
<table> with a
<tr> for each record in the
DataSource and a
<td> for each field.
Specifically, each column in a DataGrid is an instance of a class that is derived from the
DataGridColumn class. There are five built-in DataGrid column types:
Each of these column types presents data or provides some sort of interface to allow the user to interact with the DataGrid. For example, the BoundColumn displays the value of a
DataSource field as plain text, while the HyperLinkColumn displays a hyperlink whose text and URL portions can be
DataSource fields. In addition to these built-in column types, custom DataGrid column types can be created by creating a class that is derived from the
DataGridColumn class. (An example of creating a column that extends the BoundColumn functionality in limiting the number of characters displayed can be seen in Creating a Custom DataGridColumn Class.)
With the variety of DataGrid column types, it might not make sense as to why the DataGrid's rendered HTML markup is not highly customizable. Realize that while each DataGrid column type emits different HTML when rendered, each column is wrapped in a set of
<td> tags, and each row is contained in a set of
<tr> tags. So, even though a TemplateColumn can be used to customize the HTML output of a particular column for each row, the DataGrid will still render as an HTML
<table> with a
<tr> for each row and a
<td> for each column. This limitation of the DataGrid prohibits more creative displays of data. For example, if you want to display, say, five records per table row, the DataGrid is not a candidate; rather, you must use either the DataList or Repeater. Furthermore, if you want your data to display in HTML markup other than a
<table>, you are flat out of luck with the DataGrid.
A second disadvantage of the DataGrid is its performance. The DataGrid has the worst performance out of the three data Web controls. On top of this, the ViewState produced by the DataGrid—especially DataGrids with a large number of rows—can be extremely large. If you are using a DataGrid simply to display data, you can turn off the ViewState, but this is not an option when utilizing the DataGrid's sorting, paging, or editing features.
To measure the performance of the DataGrid, I used Microsoft's free Web Application Stress Tool (WAST). The precise testing conditions and WAST settings are listed at the end of this article in the "Benchmarks Settings" section. Also, the code used for the tests is available for download at the end of this article.
The Web Application Stress Tool bombards the Web server with requests to a specific set of URLs. For each of these tests I had one URL continually requested as fast as possible for one minute. WAST reports a number of performance metrics; the one I decided to concentrate on was requests per second, which indicates how many times the Web server could execute the ASP.NET Web page per second.
Two tests were run against a simple DataGrid that merely displayed data. Specifically, the DataGrid displayed four fields from the Northwinds database's Customers table (The Customers table contains a total of 91 records.). The DataGrid's
AutoGenerateColumns property was set to True. The first test placed the DataGrid inside a Web form (a
<form runat="server">), while the second one did not. By putting a control in the Form and not explicitly setting its
EnableViewState property to False, the control persists its state using the ViewState. Creating this ViewState entry can be a time-consuming process, reducing the overall requests per second that can be processed, as the results show in Figure 1.
Figure 1: Requests Per Second for the DataGrid
As we will see when examining the DataList and Repeater, both these controls offer better performance than the DataGrid.
Recall that the DataGrid renders as an HTML
<table>, which each
DataSource record as a table row (
<tr>) and each record field as a table column (
<td>). At times you might want more control over the presentation of data. For example, you might want to have the data displayed in an HTML
<table>, but rather than have one record per row, you might want to display five records per row. Alternatively, you might not want to have the data displayed in a
<table> tag at all, but rather have each element displayed in a
The DataList abandons the "column" notion adopted by the DataGrid. Instead, the DataList's display is defined via templates. With a template, the developer can specify both a mix of HTML syntax and databinding syntax. The HTML syntax is regular HTML markup; databinding syntax is delimited by the
%> tags, and is used to emit contents from the
DataSource record used in constructing a given DataList item. For example, the following ItemTemplate will display the
<asp:DataList runat="server" id="myDataList"> <ItemTemplate> <%# DataBinder.Eval(Container.DataItem, "CompanyName") %> </ItemTemplate> </asp:DataList>
In addition to the databinding syntax, the template may contain HTML markup. By updating the above template, we can have it so that the
CompanyName field is displayed in a bold font, while the
ContactName field is displayed beneath the
CompanyName field in a non-bold font:
<asp:DataList runat="server" id="myDataList"> <ItemTemplate> <b><%# DataBinder.Eval(Container.DataItem, "CompanyName") %></b> <br /> <%# DataBinder.Eval(Container.DataItem, "ContactName") %> </ItemTemplate> </asp:DataList>
For each record in the DataList's DataSource, the ItemTemplate's databinding syntax is evaluated. The output of the databinding syntax, in addition with the HTML markup, specifies the HTML that is rendered for the DataList item. Along with the ItemTemplate the DataList supports six other templates for a total of seven:
Note that the DataGrid's TemplateColumn only supports four templates: ItemTemplate, HeaderTemplate, FooterTemplate and EditItemTemplate.
By default, the DataList displays each item as a row in an HTML
<table>. However, by setting the
RepeatColumns property, you can specify how many DataList items should appear per table row. In addition to being able to specify how many DataList items to show per row of the HTML
<table>, you can also specify that the contents of the DataList should be displayed using
<span> tags instead of a
<table> tag. The DataList's
RepeatLayout property, which can be set to either Table or Flow, dictates whether the data in the DataList is rendered in an HTML
<table> or in
With its templates and
RepeatLayout properties, it's obvious that the DataList allows for much more customization of the rendered HTML markup than the DataGrid. This increased customization can lead to more user-friendly displays of data with the DataList, as the DataGrid's "single HTML
<table> with one table row per
DataSource record" model might not always be the best fit for presenting information. However, to ascertain the usability of the DataList it is not sufficient just to examine the customization improvements over the DataGrid; we must also compare the DataGrid's sorting, paging, and editing functionality to the DataList's.
With its EditItemIndex template and EditCommand, UpdateCommand, and CancelCommand events, the DataList can support inline editing. However, adding such functionality with the DataList takes more development time than with the DataGrid. This disparity in development time is due to two reasons:
- The Edit/Update/Cancel buttons that can be created in a DataGrid via the EditCommandColumn column type, must be manually added to the DataList, and
- The DataGrid BoundColumn column types automatically use a TextBox Web control for the editing interface, whereas with the DataList you must explicitly specify the editing interface for the item being edited via the EditItemTemplate.
While inline editing with the DataList is not terribly difficult, the same cannot be said for sorting and paging of the DataList's data. While such functionality is most definitely possible with some clever programming, adding such functionality to a DataList would take significant development time. Therefore, if it is a requisite that the end-user can sort and page the data, it is likely best to choose the DataGrid over the DataList.
The performance of the DataList is better than that of the DataGrid, most noticeably so when the DataList is in a Web form. Figure 2 shows the results of the Web Application Stress Tool test on the DataList.
Figure 2: Requests Per Second for the DataList
As the results in Figure 2 show, the DataList outperforms the DataGrid most noticeably when the Web controls are placed within a Web form (thereby causing the Web control to emit its ViewState).
The Repeater Web control offers the most flexibility in the rendered HTML of all three data Web controls. Unlike the DataGrid or DataList, both of which automatically encase its developer-specified content within predetermined HTML markup, when rendered the Repeater emits strictly the HTML markup you specify. For this reason, if you wish to display data in some way other than in an HTML
<table> or in a series of
<span> tags, you must use the Repeater control.
When using the Repeater, like with the DataList, you specify the markup using templates. The Repeater contains the following five templates:
The HeaderTemplate and FooterTemplate specify the HTML markup to appear before and after the data being bound to the Repeater. The AlternatingItemTemplate and ItemTemplate specify the HTML markup and databinding syntax used to render each record of the Repeater's
DataSource. For example, imagine that you were binding a DataSet containing employee information to the Repeater, and that one of the fields in the DataSet was
EmployeeName. If you wanted to display a list of employees on a Web page in an unordered list, you could use the following Repeater syntax:
<asp:Repeater runat="server" id="rptEmployees"> <HeaderTemplate> <ul> </HeaderTemplate> <ItemTemplate> <li><%# DataBinder.Eval(Container.DataItem, "EmployeeName") %></li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater>
The Repeater class is not derived from the
WebControl class, like the DataGrid and DataList. Therefore, the Repeater lacks the stylistic properties common to both the DataGrid and DataList. What this boils down to is that if you want to format the data displayed in the Repeater, you must do so in the HTML markup. For example, in our example above, if we wanted to display the employee names in a bold font we'd have to alter the ItemTemplate to include an HTML bold tag, like so:
<ItemTemplate> <li><b><%# DataBinder.Eval(Container.DataItem, "EmployeeName") %></b></li> </ItemTemplate>
Whereas with the DataGrid or DataList, we could have made the text appear in a bold font by setting the control's
ItemStyle-Font-Bold property to True.
The Repeater's lack of stylistic properties can drastically add to the development time metric. For example, imagine that you decide to use the Repeater to display data that needs to be bold, centered, and displayed in a particular font-face with a particular background color. While all this can be specified using a few HTML tags, these tags will quickly clutter the Repeater's templates. Such clutter makes it much harder to change the look at a later date, especially for others working on the project who have to wade through the mess of HTML syntax. Compare this to specifying the formatting for a DataGrid or DataList. With either of these two controls, you can leave the templates clutter-free by specifying the DataGrid or DataList's stylistic properties. Additionally, the stylistic properties of the DataGrid and DataList can be set automatically with tools like Microsoft Visual Studio® .NET or the ASP.NET Web Matrix.
Along with its increased development time, the Repeater also lacks any built-in functionality to assist in supporting paging, editing, or editing of data. Due to this lack of feature-support, the Repeater scores poorly on the usability scale. Of course, if all you are interested in is displaying data without any fancy bells or whistles, the Repeater's lack of features in not a major detractor. I stress the word "if" because typically once a Web application is deployed users find that they want additional features, such as sorting, paging, and editing.
The Repeaters one redeeming quality is—not surprisingly—its performance. The Repeater's performance is slightly better than that of the DataList's, and is more noticeably better than that of the DataGrid's. Figure 3 shows the number of requests per second the Repeater could handle versus the DataGrid and DataList.
Figure 3: Requests per Second for the Repeater
When displaying data in an ASP.NET Web page, many Web developers choose the data Web control they are most familiar with, which is typically the DataGrid. However, such blind decisions are not wise as there is no universally "best" data Web control. Rather, when deciding what data Web control to use for a given Web page, ask yourself a variety of questions to determine which control is best suited for the task at hand. Do you want to allow the user to sort through the data? Does the data need to be presented in a format other than an HTML
<table>? Will this page be heavily visited, thereby making performance a key concern?
The DataGrid Web control provides the greatest feature set of the three data Web controls, with its ability to allow the end-user to sort, page, and edit its data. The DataGrid is also the simplest data Web control to get started with, as using it requires nothing more than adding a DataGrid to the Web page and writing a few lines of code. The ease of use and impressive features comes at a cost, though, namely that of performance: the DataGrid is the least efficient of the three data Web controls, especially when placed within a Web form.
With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid. Using templates, however, typically requires more development time than using the DataGrid's column types. The DataList also supports inline editing of data, but requires a bit more work to implement than the DataGrid. Unfortunately, providing paging and sorting support in the DataList is not a trivial exercise. Making up for these lacking built-in features, the DataList offers better performance over the DataGrid.
Finally, the Repeater control allows for complete and total control of the rendered HTML markup. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. Furthermore, the Repeater does not offer built-in editing, sorting, or paging support. However, the Repeater does boast the best performance of the three data Web controls. Its performance is comparable to the DataList's, but noticeably better than the DataGrid's.
The tests were run on a Microsoft Windows® 2003 Server laptop with a 2.4 GHz Intel Pentium 4 processor, 512 MB of RAM, and a 30GB Ultra ATA hard drive. The Web server used was IIS 6.0; ASP.NET version 1.1 was used. The Web Application Stress Tool was configured to use a single thread in its testing, with no warm-up or cool-down requests made. Each test was run for a one-minute duration.
For more on performance testing of the data Web controls, as well as other great ASP.NET performance information, check out Scott Guthrie's ASP.NET Performance Talk from TechEd 2003. Additionally, you can download the demos from his talk.
- Scott Guthrie's ASP.NET Performance Talk from TechEd 2003
- Understanding the Differences Among the DataGrid, DataList, and Repeater
- An Extensive Examination of the DataGrid Web Control
- Data Access and Customization
- The DataGrid, DataList, and Repeater Forums at ASP.NET Forums
Scott Mitchell, author of five ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies for the past five years. An active member in the ASP and ASP.NET community, Scott is passionate about ASP and ASP.NET and enjoys helping others learn more about these exciting technologies. For more on the DataGrid, DataList, and Repeater controls check out Scott's book ASP.NET Data Web Controls Kick Start (ISBN: 0672325012).