Decide when to use the DataGrid, DataList, or Repeater (asp.net technical article) _ Self-Study process

Source: Internet
Author: User
Tags html tags one table
Summary: Learn about the three controls that ASP.net uses to display data: DataGrid, DataList, and Repeater. Each of these controls has unique characteristics and associated advantages and disadvantages. When creating an ASP.net application that displays data, it is important to select the correct control for this work. As you will see in this article, choose whether to use a DataGrid, DataList, or Repeater to weigh the following three factors: availability, development time, and performance. (12 page printed page)
Brief introduction
Web development has grown greatly since the advent of simple, scripting Web programming technologies such as Microsoft Active Server Pages (ASP). A large number of tedious, repetitive coding tasks that are common in traditional ASP are no longer available in Microsoft asp.net. For example, as all traditional ASP developers once knew, displaying data in a traditional ASP Web page requires 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 HTML <table>, the developer would have to generate HTML tags (markup) for <table> tags (tag), and then loop through each record in the recordset, generating a <tr& each loop Gt tags, and a number of <td> tags and the values of the recordset fields to display. Finally, after the loop, the developer needs to generate an end <table> tag.

The traditional ASP has a big drawback to this approach: it integrates HTML content tightly with the source code of ASP Web pages. Because there is no separation of code and HTML content, it is difficult to change the content of HTML, especially for graphic artists or Web designers who do not understand programming techniques. And because it requires code to retrieve the database results and generate its content, this integration of code and HTML content requires a lot of code.

Fortunately, ASP.net provides three controls, making it much simpler to display data on a asp.net Web page than the iterative approach required by traditional ASP. These three controls are DataGrid, DataList, and Repeater, which I'll call data Web controls later. Perhaps, if you've already developed ASP.net Web pages, you'll have some experience with at least one of these three controls. Typically, developers start with a learning DataGrid because the DataGrid is simple to use and has the ability to allow data sorting, paging, and editing. However, when displaying data in a asp.net Web page, the DataGrid is not always the best choice for the control.

In this article, we'll look at the unique characteristics of each control in these data Web controls. These features give each data Web control many advantages and disadvantages. Because each data Web control has some drawbacks, there is no "perfect" control available for any job. When deciding which control to use, you must weigh the pros and cons of each of the three data Web controls, and then decide which control is the most appropriate.

To assist in the comparison, we will focus on the three metrics: availability (from the perspective of the Web visitor), development time, and performance for each data Web control. Let's first take a quick look at the similarity between these three data Web controls. Next we'll delve into the DataGrid, then study DataList, and finally look at Repeater. For each control, we'll look at the functionality of these controls and discuss how their feature sets affect these metrics.

Back to the top of the page
Similarity between data Web controls
Before studying the differences between data Web controls, which make them different from other controls, look at their similarities first. At a higher level, the basic similarity is that the DataGrid, DataList, and repeater are all designed to perform roughly the same thing: displaying data. Another similarity binds data to the code required by the data Web control. Specifically, you need only the following two lines of code:

Datawebcontrolid.datasource = Somedatasource
Datawebcontrolid.databind ()

Typically, the Somedatasource object that is assigned to the DataSource property of a data Web control is a dataset, SqlDataReader, OleDbDataReader, or a collection (such as Array, ArrayList, or Syste M.collections one of the other classes in the namespace. However, any object that implements the IEnumerable interface can be bound to a data Web control.

The DataBind () method enumerates the records in the specified DataSource. For each record in DataSource, an item is created and appended to the items collection of the data Web control. Each item in a data Web control is a class instance. The specific class that is used for each item of the control depends on the data Web control. For example, each item in the DataGrid is an instance of the DataGridItem class, and each item in the Repeater is an instance of the RepeaterItem class.

Each data Web control uses a different class for each of its items, because the way these items are rendered determines the HTML markup generated by the data Web control. For example, the DataGridItem class is derived from the TableRow class, which means that each datagriditem is rendered more or less as a table row. This is interesting because the DataGrid is designed to display data in tabular form within HTML <table> markup, and each item is rendered as a single line in HTML <table>. Repeater, on the other hand, is designed to allow full customization of its output. Therefore, it is not surprising that the RepeaterItem class does not derive from the TableRow class.

Another similarity between data Web controls is that each control can use a template to provide highly customizable output. DataList and Repeater controls must specify their contents using templates, and the DataGrid can choose to use templates for specific columns through the TemplateColumn column type (we'll discuss different Da in the next section, "studying DataGrid Web controls" Tagrid column type).

The last thing to note is that the DataGrid and DataList controls derive from the WebControl class, and the Repeater controls are derived from the control class. The WebControl class contains many aesthetic attributes, such as BackColor, ForeColor, CssClass, BorderStyle, and so on. This means that if you use the DataGrid and DataList, you can specify style settings from properties that inherit from the WebControl class. And Repeater does not have any of these style attributes. As we will discuss in the "delving into Repeater" section, any visual settings for the Repeater output must be specified in the Repeater template.

Back to the top of the page
Research DataGrid Web Control
The DataGrid Web control is the most versatile of the three data Web controls, but it is the least flexible when customizing the actual HTML markup generated by the control. This inflexibility in rendered HTML markup is caused by the fact that the DataGrid is designed to use HTML <table> to display data in tabular form. Therefore, for each record bound to the DataGrid, a separate table row (<tr>) is created, and a separate table column (<td>) is created for each field in the record to be displayed.

The DataGrid provides a number of features that greatly improve the usability of the data to be displayed. For example, by setting the AllowSorting property of the DataGrid to True and adding a bit of source code, the developer can turn an ordinary DataGrid into a DataGrid whose data can be sorted by end users. In addition, with a little more work, the developer can enhance the functionality of the DataGrid to allow for data paging or inline editing of the data. These features significantly enhance the usability of the DataGrid.

In addition to scoring high on usability, the DataGrid provides a very short development time.  To start displaying data in a ASP.net Web page using the DataGrid, simply add the DataGrid to the Web page and write two lines of code that are necessary: the first line binds the data to the DataSource of the DataGrid, and the second row calls the DataGrid's DataBind () method. Obviously, as the number of features added to the DataGrid increases, so does the development time, but this only compares development time with other data Web controls. Suppose you want to allow sorting of the data displayed by Repeater. It is possible to add such functionality, but it takes a lot more time and effort than doing the same thing with a DataGrid.

Although the DataGrid has good usability and development time scores, the control has two inherent drawbacks. First, as mentioned earlier, the DataGrid has limited functionality in customizing the rendered HTML markup. Yes, you can customize the font, color, and borders of the DataGrid and the columns, but the fact remains that when the DataGrid displays data, the result is that each record in an HTML <table>,datasource corresponds to one of the &LT;TR Each field corresponds to one of the <td>.

Specifically, each column in the DataGrid is an instance of a class that derives from the DataGridColumn class. There are five built-in DataGrid column types:

BoundColumn

ButtonColumn

Editcolumn

HyperLinkColumn

TemplateColumn


Each column type provides data or provides some interface that allows users to interact with the DataGrid. For example, BoundColumn displays the value of the DataSource field in plain text, and HyperLinkColumn displays a hyperlink whose text and URL portions may be DataSource fields. In addition to these built-in column types, you can create custom DataGrid column types by creating derived classes of the DataGridColumn class. (For an example of creating a column that extends the BoundColumn feature to limit the number of characters displayed, see Creating a Custom datagridcolumn Class.) )

With so many types of DataGrid columns, it may not be possible to understand why the HTML markup rendered by the DataGrid cannot be highly customizable. You know, although each DataGrid column type produces different HTML when it is rendered, each column is contained in a set of <td> tags, and each row is contained in a set of <tr> tags.  Therefore, even if you can use TemplateColumn to customize the HTML output of a specific column for each row, the DataGrid is still rendered as HTML <table&gt, where each exercise takes a <tr&gt, and each column uses a <td>. This restriction of the DataGrid prohibits more creative data display. For example, if you want to display five records in each table row, you cannot use the DataGrid, and you must use DataList or Repeater. In addition, if you want to display data in HTML tags other than <table>, unfortunately, you cannot use the DataGrid.

The second disadvantage of a DataGrid is its performance. The DataGrid is the least performance of the three data Web controls. Based on this, the ViewState generated by the DataGrid-especially the datagrids with many rows-can be very large. If you are using the DataGrid only to display data, you can turn off ViewState, but you cannot do this by using the sorting, paging, or editing features of the DataGrid.

To test the performance of the DataGrid, I used Microsoft's free WEB application Stress Tool (WAST). The exact test conditions and WAST settings are listed in the "Baseline Settings" section at the end of this article. In addition, the code used for the test can also be downloaded at the end of this article.

This Web application Stress Tool sends a specific set of URL requests to the Web server. For each test, I request a URL as quickly as possible within a minute. Wast reported a number of performance metrics; one measure I want to focus on is the number of requests per second, which shows how many times a Web server can perform asp.net web pages per second.

For a simple DataGrid that only displays data, two Tests were run. Specifically, the DataGrid displays four fields from the Customers table (a total of 91 records in the Customers table) from the Northwinds database. The AutoGenerateColumns property of the DataGrid is set to True. The first test placed the DataGrid in a Web form (<form runat= "Server" >), while the second Test did not. If you place a control on a form without explicitly setting its EnableViewState property to False, the control retains its state with ViewState. Creating this ViewState item can be a time-consuming process, thus reducing the total number of requests per second that can be processed, as shown in Figure 1.



Number of requests per second in Figure 1:datagrid


As we will see in the study of DataList and Repeater, both controls provide better performance than the DataGrid.

Back to the top of the page
Analysis DataList
Remember that the DataGrid will be rendered as an HTML <table> each DataSource record as a table row (<tr>), each record field as a table column (<td>). Sometimes, you might want to control the display of data more. For example, you might want to display data in HTML <table>, but not one record per row, but five records per row. Or, you don't want to display the data in the <table> tag at all, but you want to display each element in a <span> tag.

DataList abandoned the "column" concept used in the DataGrid. Instead, the DataList display is defined by a template. With templates, developers can specify mixed HTML syntax and data-binding syntax. HTML syntax is a standard HTML tag, and the data-binding syntax is delimited with <%# and%> tags, and is used to generate content from DataSource records to construct a given DataList item. For example, the following ItemTemplate will display the DataSource field CompanyName:

<asp:datalist runat= "Server" id= "Mydatalist" >
<ItemTemplate>
<%# DataBinder.Eval (Container.DataItem, "CompanyName")%>
</ItemTemplate>
</asp:DataList>

In addition to data binding syntax, templates can contain HTML tags. By updating the template above, you can make the CompanyName field appear in bold and make the ContactName field appear in bold below the CompanyName field:

<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 DataSource, the data binding syntax for the ItemTemplate is computed. The output of the data binding syntax specifies the HTML that is rendered for the DataList item, along with the HTML tag. DataList also supports six other templates, including ItemTemplate, with seven of the following:

AlternatingItemTemplate

EditItemTemplate

FooterTemplate

HeaderTemplate

ItemTemplate

SelectedItemTemplate

SeparatorTemplate


Note that the templatecolumn of the DataGrid supports only four templates: ItemTemplate, HeaderTemplate, FooterTemplate, and EditItemTemplate.

By default, DataList displays each item as a row in HTML <table>. However, by setting the RepeatColumns property, you can specify how many DataList items each row of the table displays. In addition to specifying how many DataList items to display for each line of HTML <table>, you can also specify that the contents of the DataList should be displayed using the <span> tag instead of the <table> tag. The DataList RepeatLayout property can be set to Table or flow to indicate whether the data in DataList is rendered in HTML <table> or <span> tags.

With templates and the RepeatColumns and RepeatLayout properties, it is clear that DataList allows more customization of rendered HTML markup than the DataGrid. This enhanced customization makes it possible to use DataList to produce a more user-friendly display of data because the "single HTML <table>" model for each DataSource record that occupies one table row in the DataGrid cannot always be the best choice for displaying information. However, only a custom improvement over the DataGrid is not enough to determine the availability of DataList; We must also compare the sorting, paging, and editing capabilities of the DataGrid and DataList.

Using the EditItemIndex template and the EditCommand, UpdateCommand, and CancelCommand events, DataList can support inline editing. However, adding such functionality with DataList is longer than the development time spent using the DataGrid. The development time variance is due to the following two reasons:

• Edit/update/Cancel buttons created in the DataGrid through the EditCommandColumn column type must be manually added to the DataList, and

The DataGrid BoundColumn column type automatically uses the TextBox Web control as the editing interface, while using DataList must be explicitly specified by EditItemTemplate for the item to be edited.


While inline editing with DataList is not difficult, DataList data sorting, paging, and editing is difficult. While some flexible coding is certainly capable of doing so, adding such functionality to DataList will take considerable development time. Therefore, if the end user can sort and page the data is a necessary requirement, then it is best to choose the DataGrid rather than DataList.

The performance of DataList is better than that of the DataGrid, which is more apparent when DataList is in the Web window. Figure 2 shows the test results for the WEB application Stress Tool on DataList.



Number of requests per second in Figure 2:datalist


As the results in Figure 2 show, the Web control is much better than a DataGrid when DataList is placed inside the web window (and thus causes the Web control to generate its ViewState).

Back to the top of the page
In-depth study of Repeater
In all three data Web controls, the Repeater Web control provides the greatest flexibility in rendering HTML. The DataGrid or DataList automatically contains the developer-specified content in the preset HTML markup. Unlike them, Repeater will strictly generate the specified HTML markup when rendered. Therefore, if you do not want to display data with HTML <table> or a series of <span> tags, and you want to display the data in other ways, you must use the Repeater control.

Just like DataList, you use the Repeater to specify the tag with the template. Repeater contains the following five templates:

AlternatingItemTemplate

FooterTemplate

HeaderTemplate

ItemTemplate

SeparatorTemplate


HeaderTemplate and FooterTemplate Specify the HTML tags that appear before and after the data that is bound to Repeater. AlternatingItemTemplate and ItemTemplate Specify the HTML markup and data binding syntax for each record in the DataSource that renders the Repeater. For example, suppose you want to bind a dataset that contains employee information to Repeater, and one of the fields of that DataSet is EmployeeName. If you want to display the list of employees as unordered tables on a Web page, you can 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>

Unlike the DataGrid and DataList, the Repeater class is not derived from the WebControl class. As a result, Repeater lacks style attributes that are common to both DataGrid and DataList. This boils down to the fact that if you want to format the data that is displayed in Repeater, you must do so in the HTML tag. For example, in the above example, if you want to display the employee's name in bold, you must change the ItemTemplate to include the HTML bold tag, as follows:

<ItemTemplate>
<li><b><%# DataBinder.Eval (Container.DataItem, "EmployeeName")
%></b></li>
</ItemTemplate>

For a DataGrid or DataList, however, you can display text in bold by setting the control's Itemstyle-font-bold property to True.

Repeater lack of style attributes greatly increases the time metric for development. For example, suppose you decide to display data using Repeater, which needs to be displayed in bold, middle-aligned, and specific fonts with a specific background color. All of this is specified with several HTML tags, which quickly make the Repeater template messy. This clutter makes it much more difficult to make changes to the skin later, especially when someone else is working on the item, and you have to see a lot of HTML syntax. Compare this to the specified format for the DataGrid or DataList. For any of these two controls, you can save the template from clutter by specifying the DataGrid or DataList style properties. In addition, you can use tools to automatically set style properties for DataGrid and DataList, such as Microsoft Visual Studio. NET or asp.net Web Matrix.

In addition to extending the development time, Repeater lacks built-in features that help support paging, editing, or data editing. Due to lack of support for these features, Repeater scored low on usability assessment. Of course, if all you're interested in is displaying the data without any fancy ringtones or whistles, then Repeater's lack of functionality is not a major disadvantage. I emphasize the word "if" because, in general, once a WEB application is deployed, users will find that they need additional functionality, such as sorting, paging, and editing.

Repeater has a quality to compensate (which is not surprising), that is performance. Repeater performance is slightly better than DataList performance, much better than a DataGrid. Figure 3 shows the number of requests that repeater can handle per second and contrasts with the DataGrid and DataList.



Number of requests per second in Figure 3:repeater


Back to the top of the page
Summary
When you display data in a asp.net Web page, many developers choose the data Web control they are most familiar with, usually the DataGrid. But such blind decisions are not wise, because there is no universal "best" data Web control. When deciding which data Web control to use for a given Web page, you should consider each of the following questions yourself to determine which control is best suited to the task at hand. Do you want to allow users to sort the data? Do you want to display the data in a non-HTML <table> format? Will the page be heavily accessed, so performance is a key issue?

Because the DataGrid allows end users to sort, page, and edit its data, the DataGrid Web control in these three data Web controls provides the best set of features. Because you need to add it to a Web page and write a few lines of code when using a DataGrid, the DataGrid is also the easiest data Web control. However, easy to use and powerful features are costly, such as the cost of performance: The DataGrid is the least efficient of three data Web controls, especially when placed in a Web form.

By using templates, DataList provides more control over the appearance of the displayed data than the DataGrid. However, using a template typically requires more development time than a column type that uses a DataGrid DataList also supports inline editing of data, but it requires more effort than a DataGrid. Unfortunately, the provision of paging and sort support in DataList is not a simple matter. DataList provides better performance than the DataGrid, making up for these missing built-in features.

Finally, the Repeater control allows complete and comprehensive control over the rendered HTML markup. For Repeater, the only HTML generated is the value of the data-bound statement in the template and the HTML tag specified in the template, without generating "extra" html like the DataGrid and DataList. Because developers are required to specify a fully generated HTML tag, Repeater typically require the longest development time. Also, Repeater does not provide built-in editing, sorting, or paging support. However, the performance of Repeater is indeed the best of the three data Web controls. Its performance can be compared with DataList, but obviously better than the DataGrid.

I wish you all a happy programming!
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.