The ASP.NET ListView control enables you to bind to data items that are returned from a data source and display them. You can display data in pages. You can display items individually, or you can group them.
The ListView control displays data in a format that you define by using templates and styles. It is useful for data in any repeating structure, similar to the DataList and Repeater controls. However, unlike those controls, with the ListView control you can enable users to edit, insert, and delete data, and to sort and page data, all without code.
This topic contains:
You can bind the ListView control to data in these ways:
-
By using the DataSourceID property. This enables you to bind the ListView control to a data source control, such as the SqlDataSource control. We recommend this approach because it enables the ListView control to take advantage of the capabilities of the data source control. It also provides built-in functionality for sorting, paging, inserting, deleting, and updating. This approach also enables you to use two-way binding expressions. For more information about data source controls, see Data Source Controls Overview.
-
By using the DataSource property. This enables you to bind to various objects, which includes ADO.NET datasets and data readers and in-memory structures such as collections. This approach requires that you write code for any additional functionality such as sorting, paging, and updating.
Items that are displayed by a ListView control are defined by templates, similarly to the DataList and Repeater controls. The ListView control lets you display data as individual items or in groups.
You define the main (root) layout of a ListView control by creating a LayoutTemplate template. The LayoutTemplate must include a control that acts as a placeholder for the data. For example, the layout template might include an ASP.NET Table, Panel, or Label control. (It might also include HTML table, div, or span elements that have a runat attribute that is set to "server".) These controls will contain the output for each item as defined by the ItemTemplate template, which can be grouped in the content that is defined by the GroupTemplate template.
You define content for individual items in the ItemTemplate template. This template typically contains controls that are data-bound to data columns or other individual data elements.
Grouping Items
You can optionally group items in a ListView control by using the GroupTemplate template. You typically group items to create a tiled table layout. In a tiled table layout, the items are repeated in a row the number of times specified in the GroupItemCount property. In order to create a tiled table layout, the layout template might contain an ASP.NET Table control or an HTML table element that has a runat attribute set to "server". The group template can then contain an ASP.NET TableRow control (or an HTML tr element). The item template can contain individual controls that are inside an ASP.NET TableCell control (or an HTML td element).
You can use the EditItemTemplate template to supply data-bound UI that enables users to modify existing data items. You can use the InsertItemTemplate template to define data-bound UI that enables users to add a new data item. For more information, see Modifying Data later in this topic.
Available Templates
The following table lists all the templates that are used with the ListView control.
Creating an Item Template
The following example shows the basic structure of an item template.
<asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1"> <LayoutTemplate> <table runat="server" id="table1" runat="server" > <tr runat="server" id="itemPlaceholder" ></tr> </table> </LayoutTemplate> <ItemTemplate> <tr runat="server> <td runat="server"> <%-- Data-bound content. --%> <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' /> </td> </tr> </ItemTemplate> </asp:ListView>
To display items individually, you add a server-side control to the LayoutTemplate template and set the control's ID property to itemPlaceholder. This control is only a placeholder for the other templates, usually the ItemTemplate template. As a result, at run time, this control will be replaced with the content from the other templates.
Note: |
---|
You can change the value of the ID property that is used to identify the item container by setting the ItemPlaceholderID property to a new value. |
After you define the layout template, you add an ItemTemplate template that typically contains controls to display data-bound content. You can specify the markup to use to display each item by using the Eval method to bind the controls to values from the data source. For more information about the Eval method, see Data-Binding Expression Syntax.
You can supply additional content to render by using the ItemSeparatorTemplate template, which identifies content to include between items.
The following illustration shows a layout that displays data from the data source by using multiple table rows per item.
The following example shows how to create the layout.
<asp:ListView runat="server" ID="EmployeesListView" DataSourceID="EmployeesDataSource" DataKeyNames="EmployeeID"> <LayoutTemplate> <table cellpadding="2" runat="server" id="tblEmployees" style="width:460px"> <tr runat="server" id="itemPlaceholder"> </tr> </table> <asp:DataPager runat="server" ID="DataPager" PageSize="3"> <Fields> <asp:NumericPagerField ButtonCount="5" PreviousPageText="<--" NextPageText="-->" /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <tr runat="server"> <td valign="top" colspan="2" align="center" class="EmployeeName"> <asp:Label ID="FirstNameLabel" runat="server" Text='<%#Eval("FirstName") %>' /> <asp:Label ID="LastNameLabel" runat="server" Text='<%#Eval("LastName") %>' /> </td> </tr> <tr style="height:72px" runat="server"> <td valign="top" class="EmployeeInfo"> <asp:Label ID="JobTitleLabel" runat="server" Text='<%#Eval("JobTitle") %>' /> <br /> <asp:HyperLink ID="EmailAddressLink" runat="server" Text='<%#Eval("EmailAddress") %>' NavigateUrl='<%#"mailto:" + Eval("EmailAddress") %>' /> <br /> <asp:Label ID="PhoneLabel" runat="server" Text='<%#Eval("Phone") %>' /> </td> <td valign="top" class="EmployeeAddress"> <asp:Label ID="AddressLine1Label" runat="server" Text='<%#Eval("AddressLine1") %>' /> <br /> <asp:Panel ID="AddressLine2Panel" runat="server" Visible='<%#Eval("AddressLine2").ToString() != String.Empty %>'> <asp:Label ID="AddressLine2Label" runat="server" Text='<%#Eval("AddressLine2").ToString()%>' /> <br /> </asp:Panel> <asp:Label ID="CityLabel" runat="server" Text='<%#Eval("City") %>' />, <asp:Label ID="StateProvinceNameLabel" runat="server" Text='<%#Eval("StateProvinceName") %>' /> <asp:Label ID="PostalCodeLabel" runat="server" Text='<%#Eval("PostalCode") %>' /> <br /> <asp:Label ID="CountryRegionNameLabel" runat="server" Text='<%#Eval("CountryRegionName") %>' /> </td> </tr> </ItemTemplate> </asp:ListView>
Creating a Group Template
The following example shows how to create a group template.
<asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1" GroupItemCount="5"> <LayoutTemplate> <table runat="server" id="table1"> <tr runat="server" id="groupPlaceholder"> </tr> </table> </LayoutTemplate> <GroupTemplate> <tr runat="server" id="tableRow"> <td runat="server" id="itemPlaceholder" /> </tr> </GroupTemplate> <ItemTemplate> <td runat="server"> <%-- Data-bound content. --%> <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' /> </td> </ItemTemplate> </asp:ListView>
To display items in groups, you use a server control in the LayoutTemplate template to act as the placeholder for the group. For example, you might use a TableRow control. You set the placeholder control's ID property to groupPlaceholder. At run time, this placeholder control will be replaced with the contents of the GroupTemplate template.
You then add a placeholder control and set its ID property to itemPlaceholder. This control is only a placeholder for the other templates, usually the ItemTemplate template. As a result, at run time, this control will be replaced with the content from the other templates. The content is repeated the number of items specified by the GroupItemCount property of the ListView control.
Finally, you add an ItemTemplate template with the data-bound content to display inside the containing control for each item.
Note: |
---|
You can change the value of the ID property that is used to identify the group placeholder by setting a new value for the GroupPlaceholderID property. |
You can specify a separator between items by using the ItemSeparatorTemplate template. You can specify a separator between groups by using the GroupSeparatorTemplate property.
The following illustration shows a layout that displays multiple items from the data source per row.
The following example shows how to create the layout.
<asp:ListView runat="server" ID="ProductsListView" GroupItemCount="3" DataSourceID="ProductsSqlDataSource" DataKeyNames="ProductID"> <LayoutTemplate> <table cellpadding="2" runat="server" id="tblProducts" style="height:320px"> <tr runat="server" id="groupPlaceholder"> </tr> </table> <asp:DataPager runat="server" ID="DataPager" PageSize="9"> <Fields> <asp:NumericPagerField ButtonCount="3" PreviousPageText="<--" NextPageText="-->" /> </Fields> </asp:DataPager> </LayoutTemplate> <GroupTemplate> <tr runat="server" id="productRow" style="height:80px"> <td runat="server" id="itemPlaceholder"> </td> </tr> </GroupTemplate> <ItemTemplate> <td valign="top" align="center" style="width:100" runat="server"> <asp:Image ID="ProductImage" runat="server" ImageUrl='<%#"~/images/thumbnails/" + Eval("ThumbnailPhotoFileName") %>' Height="49" /><br /> <asp:HyperLink ID="ProductLink" runat="server" Target="_blank" Text='<% #Eval("Name")%>' NavigateUrl='<%#"ShowProduct.aspx?ProductID=" + Eval("ProductID") %>' /> </td> </ItemTemplate> </asp:ListView>
To enable users to page through data in a ListView control, you can use a DataPager control. The DataPager control can be inside the LayoutTemplate template or on the page outside the ListView control. If the DataPager control is not in the ListView control, you must set the PagedControlID property to the ID of the ListView control.
The DataPager control supports built-in paging UI. You can use the NumericPagerField object, which enables users to select a page of data by page number. You can also use the NextPreviousPagerField object. This enables users to move through pages of data one page at a time, or to jump to the first or last page of data. The size of the pages of data is set by using the PageSize property of the DataPager control. You can use one or more pager field objects in a single DataPager control.
You can also create custom paging UI by using the TemplatePagerField object. In the TemplatePagerField template, you can reference the DataPager control by using the Container property. This property provides access to the properties of the DataPager control. These properties include the starting row index, the page size, and the total number of rows currently bound to the ListView control.
The following example shows a DataPager class that is included in the LayoutTemplate template of a ListView control.
<asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1"> <LayoutTemplate> <table runat="server" id=" table1"> <tr runat="server" id="itemPlaceholder"> </tr> </table> <asp:DataPager runat="server" ID="DataPager" PageSize="5"> <Fields> <asp:NumericPagerField ButtonCount="10" PreviousPageText="<--" NextPageText="-->" /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <tr runat="server"> <%-- Data-bound content. --%> </tr> </ItemTemplate> </asp:ListView>
The following illustration shows a layout that displays links to pages of data based on the page number, using the NumericPagerField object.
The following example shows how to create the layout.
<asp:DataPager runat="server" ID="DataPager" PageSize="10"> <Fields> <asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers" NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " /> </Fields> </asp:DataPager>
The following illustration shows paging UI that displays links to the next, previous, first, and last pages of data by using the NextPreviousPagerField object. The paging UI also includes custom content from a TemplatePagerField template, which displays the current item number range and the total number of items. The TemplatePagerField template includes a text box where users can enter the number of an item to move to. The specified item is displayed as the first item on the page.
The following example shows how to create the paging UI.
<asp:DataPager runat="server" ID="EmployeesDataPager" PageSize="8"> <Fields> <asp:TemplatePagerField> <PagerTemplate> <asp:TextBox ID="CurrentRowTextBox" runat="server" AutoPostBack="true" Text="<%# Container.StartRowIndex + 1%>" Columns="1" style="text-align:right" OnTextChanged="CurrentRowTextBox_OnTextChanged" /> to <asp:Label ID="PageSizeLabel" runat="server" Font-Bold="true" Text="<%# Container.StartRowIndex + Container.PageSize >
Container.TotalRowCount ? Container.TotalRowCount : Container.StartRowIndex + Container.PageSize %>" /> of <asp:Label ID="TotalRowsLabel" runat="server" Font-Bold="true" Text="<%# Container.TotalRowCount %>" /> </PagerTemplate> </asp:TemplatePagerField> <asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true" FirstPageText="|<< " LastPageText=" >>|" NextPageText=" > " PreviousPageText=" < " /> </Fields> </asp:DataPager>
The following example shows the event handler for the TextChanged event of the TextBox control that is included in the TemplatePagerField template. The code in the handler moves to the data item that is specified by the user.
Protected Sub CurrentRowTextBox_OnTextChanged(ByVal sender As Object, _ ByVal e As EventArgs) Dim t As TextBox = CType(sender, TextBox) Dim pager As DataPager = _ CType(EmployeesListView.FindControl("EmployeesDataPager"), _ DataPager) pager.SetPageProperties(Convert.ToInt32(t.Text) - 1, _ pager.PageSize, True) End Sub
protected void CurrentRowTextBox_OnTextChanged(object sender, EventArgs e) { TextBox t = (TextBox)sender; DataPager pager = (DataPager)EmployeesListView.FindControl("EmployeesDataPager"); pager.SetPageProperties(Convert.ToInt32(t.Text) - 1, pager.PageSize, true); }
You can sort the data that is displayed in a ListView control by adding a button to the LayoutTemplate template and setting the button's CommandName property to "Sort". You set the CommandArgument property of the button to the column name that you want to sort by. Clicking the Sort button repeatedly toggles the sort direction between Ascending and Descending.
You can specify multiple column names in the CommandArgument property of the Sort button. However, the ListView control applies the sort direction to the complete list of columns. As a result, only the last column of the list has the sort direction applied. For example, if the CommandArgument contains "LastName, FirstName", clicking the Sort button repeatedly produces a sort expression like "LastName, FirstName ASC" or "LastName, FirstName DESC".
The following example shows a ListView control that includes a Sort button to sort the data by last name.
<asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1"> <LayoutTemplate> <asp:LinkButton runat="server" ID="SortButton" Text="Sort" CommandName="Sort" CommandArgument="LastName" /> <table runat="server" id="table1"> <tr runat="server" id="itemPlaceholder"> </tr> </table> <asp:DataPager runat="server" ID="DataPager" PageSize="20"> <Fields> <asp:NumericPagerField ButtonCount="10" PreviousPageText="<--" NextPageText="-->" /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <tr runat="server"> <td><asp:Label runat="server" ID="FirstNameLabel" Text='<%# Eval("FirstName")' /></td> <td><asp:Label runat="server" ID="LastNameLabel" Text='<%# Eval("LastName")' /></td> </tr> </ItemTemplate> </asp:ListView>
Setting the Sort Expression Dynamically
You can create customized sorting by setting the sort expression of a ListView control dynamically. To do so, you call the Sort method or handle the Sorting event.
The following example shows a handler for the Sorting event. The code applies the same sort direction to all the columns in the SortExpression property.
Protected Sub ContactsListView_Sorting(ByVal sender As Object, _ ByVal e As ListViewSortEventArgs) If (String.IsNullOrEmpty(e.SortExpression)) Then Return Dim direction As String = "" If Not (ViewState("SortDirection") Is Nothing) Then direction = ViewState("SortDirection").ToString() End If If direction = "ASC" Then direction = "DESC" Else direction = "ASC" End If ViewState("SortDirection") = direction Dim sortColumns As String() = e.SortExpression.Split(","c) Dim sortExpression As String = sortColumns(0) & " " & direction Dim i As Integer For i = 1 To sortColumns.Length - 1 sortExpression += ", " & sortColumns(i) & " " & direction Next i e.SortExpression = sortExpression End Sub
protected void EmployeesListView_OnSorting(object sender, ListViewSortEventArgs e) { if (String.IsNullOrEmpty(e.SortExpression)) { return; } string direction = ""; if (ViewState["SortDirection"] != null) direction = ViewState["SortDirection"].ToString(); if (direction == "ASC") direction = "DESC"; else direction = "ASC"; ViewState["SortDirection"] = direction; string[] sortColumns = e.SortExpression.Split(','); string sortExpression = sortColumns[0] + " " + direction; for (int i = 1; i < sortColumns.Length; i++) sortExpression += ", " + sortColumns[i] + " " + direction; e.SortExpression = sortExpression; }
You can create templates for the ListView control that enable users to edit, insert, or delete a single data item.
To enable users to edit a data item, you can add a EditItemTemplate template to the ListView control. When an item is switched to edit mode, the ListView control displays the item by using the edit template. The template should include data-bound controls where the user can edit values. For example, the template can include text boxes where users can edit existing values.
To enable users to insert a new item, you can add a InsertItemTemplate template to the ListView control. As with the edit template, the insert template should include data-bound controls that enable data entry. The InsertItemTemplate template is rendered either at the start or at the end of the displayed items. You specify where the InsertItemTemplate template is rendered by using the InsertItemPosition property of the ListView control.
You typically add buttons to templates to enable users to specify what action they want to take. For example, you can add a Delete button to an item template to enable users to delete that item.
You can add an Edit button to an item template to enable the user to switch to edit mode. In the EditItemTemplate you can include an Update button that enables users to save changes. You can also include a Cancel button that enables users to switch back to display mode without saving changes.
You define the action that a button will take by setting the CommandName property of the button. The following table lists values for the CommandName property that the ListView control has built-in behavior for.
For an example of a ListView control that is configured to enable editing, deleting, and inserting, see Walkthrough: Modifying Data Using the ListView Web Server Control.
The ListView control does not support style properties such as BackColor and Font. In order to apply styles to the ListView control, you must use cascading style sheets (CSS) classes or inline style elements for individual controls inside the ListView templates.
Some objects support properties that enable you to style elements of the output. For example, the NumericPagerField object includes the following properties:
-
A NumericButtonCssClass property that enables you to specify the CSS class name for the buttons that move to pages of data by number.
-
A CurrentPageLabelCssClass property that enables you to specify the CSS class name for the current page number.
-
A NextPreviousButtonCssClass property that enables you to specify the CSS class name for the buttons that move to the next or previous group of numeric buttons.
The following table lists the key classes that are related to the ListView control.
Class | Description |
---|---|
A server control that displays the values of a data source by using user-defined templates. You can configure the control to enable users to select, sort, delete, edit, and insert records. | |
An object that represents an item in the ListView control. | |
An object that represents a data item in the ListView control. | |
An enumeration that identifies the function of items in a ListView control. | |
A server control that provides paging functionality for controls that implement the IPageableItemContainer interface, such as the ListView control. | |
A DataPager field that enables users to select a page of data by page number. | |
A DataPager field that enables users to move through pages of data one page at a time, or to jump to the first or last page of data. | |
A DataPager field that enables users to create a custom paging UI. |
The following sections include code examples for using the ListView control.