ListView Web Server Control Overview

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:

  • Binding Data to the ListView Control

  • Creating Templates for the ListView Control

  • Paging Data

  • Sorting Data

  • Modifying Data

  • Applying Styles to ListView Items

  • Class Reference

  • Code Examples

  • Additional Resources

Binding Data to the ListView Control

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.

  • 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.

Back to top

Creating Templates for the ListView Control

Items that are displayed by a ListView control can be defined by templates, similar to how templates are used in the DataList and Repeater controls. The ListView control lets you display data as individual items or in groups.

If you use layout templates, you can 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".) If you do not define a layout template, a placeholder control is automatically inserted. This placeholder control contains 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.

Note

If no layout is defined, if you set the GroupItemCount property to a value greater than zero, and if you also define an ItemTemplate property, the control functions as if the LayoutTemplate property were defined. If you define a LayoutTemplate property, a PlaceHolder control must exist.

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.

  • LayoutTemplate
    Identifies the root template that defines the main layout of the control. It contains a placeholder object, such as a table row (tr), div, or span element. This element will be replaced with the content that is defined in the ItemTemplate template or in the GroupTemplate template. It might also contain a DataPager object.

  • ItemTemplate
    Identifies the data-bound content to display for single items.

  • ItemSeparatorTemplate
    Identifies the content to render between single items.

  • GroupTemplate
    Identifies the content for the group layout. It contains a placeholder object, such as a table cell (td), div, or span that will be replaced with the content defined in the other templates, such as the ItemTemplate and EmptyItemTemplate templates.

  • GroupSeparatorTemplate
    Identifies the content to render between groups of items.

  • EmptyItemTemplate
    Identifies the content to render for an empty item when a GroupTemplate template is used. For example, if the GroupItemCount property is set to 5, and the total number of items returned from the data source is 8, the last row of data displayed by the ListView control will contain three items as specified by the ItemTemplate template, and two items as specified by the EmptyItemTemplate template.

  • EmptyDataTemplate
    Identifies the content to render if the data source returns no data.

  • SelectedItemTemplate
    Identifies the content to render for the selected data item to differentiate the selected item from the other displayed items.

  • AlternatingItemTemplate
    Identifies the content to render for alternating items to make it easier to distinguish between consecutive items.

  • EditItemTemplate
    Identifies the content to render when an item is being edited. The EditItemTemplate template is rendered in place of the ItemTemplate template for the data item being edited.

  • InsertItemTemplate
    Identifies the content to render when an item is being inserted. The InsertItemTemplate template is rendered in place of an ItemTemplate template at either the start of the items displayed by the ListView control, or at the end. You can specify where the InsertItemTemplate template is rendered by using the InsertItemPosition property of the ListView control.

Creating an Item Template

The following example shows the basic structure of an item template that uses a layout template.

<asp:ListView runat="server" ID="ListView1" 
    DataSourceID="SqlDataSource1">
  <LayoutTemplate>
    <table runat="server" id="table1" >
      <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>

The following example shows the basic structure of an item template that uses a layout template.

<asp:ListView runat="server" ID="ListView1" 
    DataSourceID="SqlDataSource1">
  <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 Expressions Overview.

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.

ListView using multiple 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.

Multiple items per row in a ListView control

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>

Back to top

Paging Data

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.

By default, if a user selects a row on a page, the same row is selected on each page. If you want to persist selection only for the row that the user has selected (as identified by the row's data key), you can set the EnablePersistedSelection property to true.

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.

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.

Using the TemplatePagerField object

The following example shows how to create the paging UI.

<asp:DataPager runat="server" ID="EmployeesDataPager" PageSize="8">
  <Fields>
    <asp:TemplatePagerField>
      <PagerTemplate>
        &nbsp;
        <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);
}

Back to top

Sorting Data

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;
}

Back to top

Modifying Data

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.

  • Select
    Displays the content of the SelectedItemTemplate template for the selected item.

  • Insert
    In an InsertItemTemplate template, specifies that the contents of data-bound controls should be saved in the data source.

  • Edit
    Specifies that the ListView control should switch to edit mode and display the item by using the EditItemTemplate template.

  • Update
    In an EditItemTemplate template, specifies that the contents of data-bound controls should be saved in the data source.

  • Delete
    Deletes the item from the data source.

  • Cancel
    Cancels the current action. When the EditItemTemplate template is displayed, canceling the action displays the SelectedItemTemplate template if the item is the current selected item; otherwise the ItemTemplate template is displayed. When the InsertItemTemplate template is displayed, canceling the action displays an empty InsertItemTemplate template.

  • (Custom value)
    By default, takes no action. You can supply a custom value for the CommandName property. In the ItemCommand event, you can then test for the value and take action.

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.

Back to top

Applying Styles to ListView Items

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.

Back to top

Class Reference

The following table lists the key classes that are related to the ListView control.

Class

Description

ListView

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.

ListViewItem

An object that represents an item in the ListView control.

ListViewDataItem

An object that represents a data item in the ListView control.

ListViewItemType

An enumeration that identifies the function of items in a ListView control.

DataPager

A server control that provides paging functionality for controls that implement the IPageableItemContainer interface, such as the ListView control.

NumericPagerField

A DataPager field that enables users to select a page of data by page number.

NextPreviousPagerField

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.

TemplatePagerField

A DataPager field that enables users to create a custom paging UI.

Back to top

Code Examples

The following sections include code examples for using the ListView control.

How to and Walkthrough Topics

Walkthrough: Displaying, Paging, and Sorting Data Using the ListView Web Server Control

Walkthrough: Modifying Data Using the ListView Web Server Control

Back to top

See Also

Concepts

Accessibility in Visual Studio and ASP.NET

Data-Bound Web Server Controls

Data Source Web Server Controls

Other Resources

ASP.NET Globalization and Localization