The Repeater, DataList, and DataGrid Controls


ASP.NET has three primary controls for easily displaying sets of data: Repeater, DataList, and DataGrid. In this section, we’ll explain the major differences in their feature sets, examine how to use them, and discuss their limitations so that you pick the correct control for your development task.

Repeater

The Repeater control has no implicit markup to render. Instead, you are required to specify templates that indicate to the containing control which markup—typically HTML—to render for each item in the data source. Markup is specified declaratively; you don’t need to know how many items will exist when the data-binding occurs. Because the Repeater control does not offer a default rendering, it is probably the most flexible of the three controls. However, selecting, editing, and deleting items is more difficult with Repeater. Repeater does not offer a rich set of style properties to set because the appearance is controlled entirely by what is in the templates. Code Listing 3-5 shows a Repeater control in action, including using the full set of templates: HeaderTemplate, FooterTemplate, ItemTemplate, AlternatingItemTemplate, and SeparatorTemplate.

Code Listing 3-5: Repeater.aspx

start example
 <script language="C#" runat="server">
public class State {
string _name;
string _timezone;
public State(string name, string timezone) {
_name = name;
_timezone = timezone;
}
public string Name {
get { return _name; }
}
public string TimeZone {
get { return _timezone; }
}
}
protected void Page_Load(object o, EventArgs e) {
if(!IsPostBack) {
ArrayList states = new ArrayList();
states.Add(new State("Washington", "Pacific"));
states.Add(new State("Utah", "Mountain"));
states.Add(new State("Wisconsin", "Central"));
states.Add(new State("New York", "Eastern"));

repeaterVertical.DataSource = states;
repeaterHorizontal.DataSource = states;

repeaterVertical.DataBind();
repeaterHorizontal.DataBind();
}
}
</script>
<form runat="server">
<asp:Repeater runat="server" >
<HeaderTemplate>
<table><tr><th>State</th><th>TimeZone</th></tr>
</HeaderTemplate>
<ItemTemplate>
<tr bgcolor="blue">
<td><%#((State)(Container.DataItem)).Name) %></td>
<td><%#DataBinder.Eval(Container,
"DataItem.TimeZone") %></td>
</tr>
</ItemTemplate>
<SeparatorTemplate>
<tr bgcolor="white"><td><hr></td></tr>
</SeparatorTemplate>
<AlternatingItemTemplate>
<tr bgcolor="red">
<td><%#((State)(Container.DataItem)).Name %></td>
<td><%#DataBinder.Eval(Container,
"DataItem.TimeZone") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate></table></FooterTemplate>
</asp:Repeater>

<hr/>

<asp:Repeater runat="server" >
<HeaderTemplate>
<table><tr><th>State<br/>TimeZone</th>
</HeaderTemplate>
<ItemTemplate>
<td bgcolor="blue">
<%#DataBinder.Eval(Container.DataItem,
"Name") %><br />
<%#DataBinder.Eval(Container.DataItem,
"TimeZone") %>
</td>
</ItemTemplate>
<AlternatingItemTemplate>
<td bgcolor="red">
<%#DataBinder.Eval(Container.DataItem,
"Name") %><br />
<%#DataBinder.Eval(Container.DataItem,
"TimeZone") %>
</td>
</AlternatingItemTemplate>
<FooterTemplate></tr></table></FooterTemplate>
</asp:Repeater>
</form>
end example

The output from Code Listing 3-5 is shown in Figure 3-2. The script block in Repeater.aspx first contains a simple class that holds a state name and its time zone. In the Page_Load method, a small set of these objects is created and added to an ArrayList, which is then set as the data source property of the two Repeater controls on the page. The first Repeater control displays the items from the list horizontally in a table, whereas the second Repeater control displays them vertically. Notice that the header and footer templates are used to render the beginning and ending tags of the table. The ItemTemplate and AlternatingItemTemplate are then used in turn for the items from the data source.

click to expand
Figure 3-2: The Repeater control allows for flow and column layout

Another aspect to note about Code Listing 3-5 is the different syntax used in the data-binding expressions. In the first data-binding instance, the RepeaterItem object returned from Container.DataItem is explicitly cast to the State object type stored in the data source. The Name property accessor of the State object is then accessed directly. In the second data-binding instance, the DataBinder.Eval method is used to automatically perform reflection on the Container to retrieve the TimeZone property of the State object, which is stored in the DataItem property. In the second Repeater control, an alternate form of the DataBinder.Eval method is used in which the first parameter is resolved directly to the item, and the property is then resolved through reflection. These two syntax statements can be used interchangeably.

DataList

The DataList control provides rendering behavior in addition to supporting a set of templates for controlling the control’s appearance. Unlike the Repeater control, which supports only flow layout rendering, the DataList control supports both table and flow layout. In table layout, the templates are rendered as part of a Table element. In flow layout, the templates are rendered inside span tags. With either type of layout, the DataList allows you to control whether the items are repeated in a horizontal or vertical orientation as well as how many columns of items appear across the page. Code Listing 3-6 has an example of the DataList control. In addition to the templates supported by the Repeater control, DataList supports EditItemTemplate and SelectedItemTemplate for editing and selection, respectively.

Code Listing 3-6: DataList.aspx

start example
 <script language="C#" runat="server">
public class State {
string _name;
string _timezone;
public State(string name, string timezone) {
_name = name;
_timezone = timezone;
}
public string Name {
get { return _name; }
}
public string TimeZone {
get { return _timezone; }
}
}
protected void Page_Load(object o, EventArgs e) {
if(!IsPostBack) {
ArrayList states = new ArrayList();
states.Add(new State("Washington", "Pacific"));
states.Add(new State("Utah", "Mountain"));
states.Add(new State("Wisconsin", "Central"));
states.Add(new State("New York", "Eastern"));

datalist.DataSource = states;
datalist.DataBind();
datalist.SelectedIndex = 0;
}
}
</script>
<form runat="server">
<asp:DataList runat="server" BackColor="tan"
RepeatDirection="Vertical" BorderWidth="1"
BorderColor="Black" Repeatcolumns="2"
CellSpacing="3" CellPadding="4" >
<SelectedItemStyle BackColor="beige" >
</SelectedItemStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Name") %> is in
<%# DataBinder.Eval(Container, "DataItem.Timezone") %>
</ItemTemplate>
</asp:DataList>
</form>
end example

DataGrid

The DataGrid control is the most commonly used of the three controls. It renders the items as a table with each item contained inside a single row, so it does not support a choice of column or flow layout. Unlike the Repeater and DataList controls, the DataGrid control supports paging of content as well as sorting. Although the DataGrid control is generally easier to use, it doesn’t offer you a high degree of templating control with the exception of offering support for templating entire columns. Code Listing 3-7 shows a basic DataGrid control bound to data created directly on the page. Additional code samples follow that demonstrate how to accomplish specific tasks with the DataGrid control.

Code Listing 3-7: DataGrid.aspx

start example
 <%@Import namespace="System.Data" %>
<script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
datagrid.DataSource = GetData();
DataBind();
}

DataTable GetData() {
DataTable data = new DataTable();
data.Columns.Add(new DataColumn("TheID", typeof(Int32)));
data.Columns.Add(new DataColumn("Name", typeof(string)));
data.Columns.Add(new DataColumn("TimeZone", typeof(string)));

DataRow dr;
dr = data.NewRow();
dr[0] = 1; dr[1] = "Washington"; dr[2] = "Pacific";
data.Rows.Add(dr);
dr = data.NewRow();
dr[0] = 2; dr[1] = "Utah"; dr[2] = "Mountain";
data.Rows.Add(dr);
dr = data.NewRow();
dr[0] = 3; dr[1] = "Wisconsin"; dr[2] = "Central";
data.Rows.Add(dr);
dr = data.NewRow();
dr[0] = 4; dr[1] = "New York"; dr[2] = "Eastern";
data.Rows.Add(dr);
dr = data.NewRow();
dr[0] = 5; dr[1] = "Florida"; dr[2] = "Eastern";
data.Rows.Add(dr);

return data;
}
</script>
<form runat="server">
<asp:DataGrid runat="server" />
</form>
end example

Figure 3-3 shows the basic rendering that this approach produces. In the “Adding Styles To the DataGrid” section later in this chapter, Code Listing 3-9 adds styles and templated header text to demonstrate the flexibility and sophisticated user interface available in the DataGrid control.

click to expand
Figure 3-3: Basic DataGrid rendering

In DataGrid.aspx, the data source is a DataTable object created directly on the page; however, this data-binding approach is not the most common. When a Web application needs to provide support for manipulating and modifying data, a DataSet object is populated from a back-end database. The local view of the data can thus be manipulated over time through a series of requests and committed back to the database later. On the other hand, when a Web application needs only to display and not update data, using SqlDataReader is a better choice, since SqlDataReader provides a read-only view of the data and has less overhead than the DataSet. However, be aware that when using SqlDataReader, the DataGrid will not perform sorting and paging directly. If sorting and pagination are required, use a DataSet or a DataView.

Tip

For frequently accessed but rarely changed data, use the application cache or partial page caching (discussed in Chapter 6) to cut down on trips to the database.

start sidebar
Managing ViewState Size

When ViewState is enabled, as it is by default, the data from the data source makes a round trip between the client and server on each request. When the data is significantly large, this round trip can have a negative impact on the user experience. Look at the size of the ViewState for the DataGrid control by using tracing (discussed in Chapter 10) to understand exactly what kind of impact the ViewState is having on page size.

If ViewState size is problematic for an application, a couple of solutions are available. First, you can completely disable ViewState in configuration or on the page or for an individual control. Without ViewState, the DataGrid control can no longer automatically store information about the paging state, the item being edited, or the current sort expression. You would need to maintain this data separately.

Second, you can simply reduce ViewState by following these steps:

  1. Set AutoGenerateColumns to false and explicitly declare only those columns that are necessary.

  2. Set the styles in the code explicitly instead of establishing them declaratively.

  3. Do not use the DataKeyField member.

end sidebar




Microsoft ASP. NET Coding Strategies with the Microsoft ASP. NET Team
Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Team (Pro-Developer)
ISBN: 073561900X
EAN: 2147483647
Year: 2005
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net