Bagikan melalui


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

In this walkthrough, you will work with the ListView control, which enables you to display data from a data source in a format that you define by using templates. By working with templates, you can have complete control over the layout and appearance of the data in the control. The ListView control automatically supports edit, insert, and delete operations as well as sorting and paging functionality.

The walkthrough illustrates the following tasks:

  • Using the ListView control to display data from a database.

  • Adding paging functionality to the ListView control.

  • Adding sorting functionality to the ListView control.

A full listing for the page that you create in this walkthrough is listed at the end of the topic.

Prerequisites

In order to complete this walkthrough, you will need:

  • Visual Studio 2008 or Visual Web Developer 2008 Express Edition.

  • SQL Server Express Edition. If you have SQL Server installed, you can use that instead, but you must make small adjustments to some of the procedures.

  • The AdventureWorks database installed on your computer. For information about how to download and install the SQL Server sample AdventureWorks database, see Installing Sample Databases for Express Editions on the Microsoft SQL Server Web site.

  • A user name and password for a SQL Server account that has access to the AdventureWorks database.

Creating the Web Site

If you have already created a Web site (for example, by completing Walkthrough: Creating a Basic Web Page in Visual Web Developer ), you can use that Web site and go to the next section. Otherwise, create a new Web site and page by following these steps.

To create a file system Web site

  1. Open Visual Studio 2008 or Visual Web Developer 2008 Express Edition.

  2. On the File menu, click New, and then click Web Site. If you are using Visual Web Developer Express, on the File menu, click New Web Site.

    The New Web Site dialog box is displayed.

  3. Under Visual Studio installed templates, click ASP.NET Web Site.

  4. In the first Location box, select File System, and in the second box, enter the name of the folder where you want to keep the pages of the Web site.

    For example, enter the folder name C:\WebSites\DisplayData.

  5. In the Language list, click the programming language that you prefer to work in.

  6. Click OK.

    Visual Studio creates the folder and a new page named Default.aspx.

Displaying and Paging Through Data in the ListView Control

To display data on an ASP.NET Web page, you need the following:

  • A connection to a data source such as a database. In the following procedure, you will create a connection to the SQL Server AdventureWorks database.

  • A data source control on the page, which interacts with the data source (the database) to read and write data. In this walkthrough, you will use a SqlDataSource control that interacts with the SQL Server AdventureWorks database.

  • A control on the page to display the data. In the following procedure, you will display data in a ListView control, which gets its data from the SqlDataSource control.

To display and page through data in the ListView control

  1. If the Web site does not have an App_Data folder, in Solution Explorer, right-click the project, click Add ASP.NET Folder, and then click App_Data.

  2. In Solution Explorer, right-click the App_Data folder, and then click Add Existing Item.

    The Add Existing Item dialog box is displayed.

  3. Enter the location of the AdventureWorks database file (AdventureWorks_Data.mdf).

    By default, the .mdf file is installed in the path C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf.

    Note

    This procedure will create a copy of the database file in the project. The database file is large. If it is impractical to make a copy of the database, you can connect to it by using an alternative method, such as attaching the database file directly. However, the procedure for doing this is not covered in this walkthrough.

  4. Switch to or open the Default.aspx file.

  5. Switch to Design view.

  6. From the Data tab of the Toolbox, drag a ListView control onto the page.

    ListView Control

  7. On the Common ListView Tasks menu, in the ChooseData Source drop-down list, click <New data source…>.

    The Data Source Configuration wizard is displayed.

  8. Click Database.

    This specifies that you want to get data from a database that supports SQL statements, which includes SQL Server and other OLE-DB–compatible databases.

  9. In the Specify an ID for the data source box, a default data source control name, SqlDataSource1, is displayed. You can leave this name.

    Data Source Configuration Wizard

  10. Click OK.

    The Configure Data Source wizard is displayed.

  11. Under Which data connection should your application use to connect to a database?, select AdventureWorks_Data.mdf from the list.

  12. Click Next.

    The wizard displays a page where you can specify that you want to store the connection string in the configuration file. Storing the connection string in the configuration file has two advantages:

    • It can be more secure than storing it in the page.

    • You can use the same connection string in multiple pages.

  13. Make sure that the Yes, save this connection as check box is selected, and then click Next. You can leave the default connection string name.

    The wizard displays a page where you can specify what data you want to retrieve from the database.

  14. Select the Specify a custom SQL statement or stored procedure option.

    Configure the Select Statement

    Note

    Typically, you would use the option Specify columns from a table or view. However, because the AdventureWorks database has schema names, in this walkthrough you will create a custom SQL statement.

  15. Click Next

  16. In the Define Custom Statements or Stored Procedures page, enter the following SQL query, which retrieves contact data from the AdventureWorks database.

    SELECT  ContactID, FirstName, LastName, EmailAddress
    FROM    Person.Contact
    

    You can also click Query Builder and use the Query Builder window to create a query and then validate it by using the Execute Query button.

    Note

    The wizard lets you specify selection criteria (Where clauses) and other SQL query options. For this walkthrough, you will create a simple statement that has no selection or sort criteria.

  17. Click Next.

  18. Click Test Query to make sure that you are retrieving the data that you want.

  19. Click Finish.

    The wizard creates a SqlDataSource control and adds it to the page. The ListView control that you added earlier is bound to the SqlDataSource control.

    If you view the properties for the SqlDataSource control, you will see that the wizard has created values for the ConnectionString and SelectCommand properties.

  20. Right-click the ListView control, click Show Smart Tag.

  21. On the Common ListView Tasks menu, click Configure ListView.

    The Configure ListView dialog box is displayed.

  22. Select Enable Paging.

    Note

    You might also want to select a different style, which can make it easier to view the data. To do this, under Select a Style, select a style such as Colorful.

    The wizard creates the templates for the ListView control, based on the columns in the query. You can customize the layout by editing the templates that contain the layout elements, controls, and binding expressions.

    Configure ListView

  23. Click OK.

    ListView Control

Before proceeding, you can test the ListView control.

To test the ListView control

  1. Press CTRL+F5 to run the page.

    The ListView control is displayed with ContactID, FirstName, LastName, and EmailAddress columns.

  2. Click the First, Previous, Next, and Last buttons at the bottom of the page in order to page through data.

  3. When you have finished, close the browser.

Adding Sort Capability to the ListView Control

You will now add sort capability to the ListView control. You can provide this capability by adding a button to the ListView control and configuring the button.

To add sorting capability to the ListView control

  1. In the Default.aspx file, switch to Source view.

    Note

    Typically, you can modify the templates for the ListView control by using the designer. However, for layouts based on tables, such as Grid, you must change the code directly.

  2. Find the LayoutTemplate element inside the ListView control.

  3. From the Standard tab of the Toolbox, drag two Button controls before the markup code for the DataPager control.

  4. In the Properties window, change the properties of the buttons as follows:

    • For the first button, set the Text property to "Sort by First Name", the CommandName property to "Sort", and the CommandArgument to "FirstName".

    • For the second button, set the Text property to "Sort by Last Name", the CommandName property to "Sort", and the CommandArgument to "LastName".

    The button's CommandArgument properties are set to a sort expression. For database data, this is typically the name of a column.

  5. Save the page.

You can now test the page again.

To test sorting

  1. Press CTRL+F5 to run the page.

  2. Click the Sort by First Name and Sort by Last Name buttons to sort the data in different ways.

  3. Click a button repeatedly to switch between ascending and descending sort order.

Example

Description

The following example shows the source code for the page that you create in this walkthrough. Only the markup is shown, because you did not make any changes to the code-behind file.

Code

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>

    <asp:ListView ID="ListView1" runat="server" DataKeyNames="ContactID" 
      DataSourceID="SqlDataSource1">
      <ItemTemplate>
        <tr style="background-color: #FFFBD6;color: #333333;">
          <td>
            <asp:Label ID="ContactIDLabel" runat="server" Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
          </td>
          <td>
            <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
          </td>
          <td>
            <asp:Label ID="EmailAddressLabel" runat="server" 
              Text='<%# Eval("EmailAddress") %>' />
          </td>
        </tr>
      </ItemTemplate>
      <AlternatingItemTemplate>
        <tr style="background-color: #FAFAD2;color: #284775;">
          <td>
            <asp:Label ID="ContactIDLabel" runat="server" Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
          </td>
          <td>
            <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
          </td>
          <td>
            <asp:Label ID="EmailAddressLabel" runat="server" 
              Text='<%# Eval("EmailAddress") %>' />
          </td>
        </tr>
      </AlternatingItemTemplate>
      <EmptyDataTemplate>
        <table id="Table1" runat="server" 
          style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;">
          <tr>
            <td>
              No data was returned.</td>
          </tr>
        </table>
      </EmptyDataTemplate>
      <InsertItemTemplate>
        <tr style="">
          <td>
            <asp:Button ID="InsertButton" runat="server" CommandName="Insert" 
              Text="Insert" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" 
              Text="Clear" />
          </td>
          <td>
            &nbsp;</td>
          <td>
            <asp:TextBox ID="FirstNameTextBox" runat="server" 
              Text='<%# Bind("FirstName") %>' />
          </td>
          <td>
            <asp:TextBox ID="LastNameTextBox" runat="server" 
              Text='<%# Bind("LastName") %>' />
          </td>
          <td>
            <asp:TextBox ID="EmailAddressTextBox" runat="server" 
              Text='<%# Bind("EmailAddress") %>' />
          </td>
        </tr>
      </InsertItemTemplate>
      <LayoutTemplate>
        <table id="Table2" runat="server">
          <tr id="Tr1" runat="server">
            <td id="Td1" runat="server">
              <table ID="itemPlaceholderContainer" runat="server" border="1" 
                style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
                <tr id="Tr2" runat="server" style="background-color: #FFFBD6;color: #333333;">
                  <th id="Th1" runat="server">
                    ContactID</th>
                  <th id="Th2" runat="server">
                    FirstName</th>
                  <th id="Th3" runat="server">
                    LastName</th>
                  <th id="Th4" runat="server">
                    EmailAddress</th>
                </tr>
                <tr ID="itemPlaceholder" runat="server">
                </tr>
              </table>
            </td>
          </tr>
          <tr id="Tr3" runat="server">
            <td id="Td2" runat="server" 
              style="text-align: center;background-color: #FFCC66;font-family: Verdana, Arial, Helvetica, sans-serif;color: #333333;">
                <asp:Button ID="Button1" runat="server" Text="Sort by First Name" CommandName="Sort" CommandArgument="FirstName" />
                <asp:Button ID="Button2" runat="server" Text="Sort by Last Name" CommandName="Sort" CommandArgument="LastName" />
              <asp:DataPager ID="DataPager1" runat="server">
                <Fields>
                  <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" 
                    ShowLastPageButton="True" />
                </Fields>
              </asp:DataPager>
            </td>
          </tr>
        </table>
      </LayoutTemplate>
      <EditItemTemplate>
        <tr style="background-color: #FFCC66;color: #000080;">
          <td>
            <asp:Button ID="UpdateButton" runat="server" CommandName="Update" 
              Text="Update" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" 
              Text="Cancel" />
          </td>
          <td>
            <asp:Label ID="ContactIDLabel1" runat="server" 
              Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:TextBox ID="FirstNameTextBox" runat="server" 
              Text='<%# Bind("FirstName") %>' />
          </td>
          <td>
            <asp:TextBox ID="LastNameTextBox" runat="server" 
              Text='<%# Bind("LastName") %>' />
          </td>
          <td>
            <asp:TextBox ID="EmailAddressTextBox" runat="server" 
              Text='<%# Bind("EmailAddress") %>' />
          </td>
        </tr>
      </EditItemTemplate>
      <SelectedItemTemplate>
        <tr style="background-color: #FFCC66;font-weight: bold;color: #000080;">
          <td>
            <asp:Label ID="ContactIDLabel" runat="server" Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
          </td>
          <td>
            <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
          </td>
          <td>
            <asp:Label ID="EmailAddressLabel" runat="server" 
              Text='<%# Eval("EmailAddress") %>' />
          </td>
        </tr>
      </SelectedItemTemplate>
    </asp:ListView>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
      ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
      SelectCommand="SELECT  ContactID, FirstName, LastName, EmailAddress FROM Person.Contact">
    </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>

    <asp:ListView ID="ListView1" runat="server" DataKeyNames="ContactID" 
      DataSourceID="SqlDataSource1">
      <ItemTemplate>
        <tr style="background-color: #FFFBD6;color: #333333;">
          <td>
            <asp:Label ID="ContactIDLabel" runat="server" Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
          </td>
          <td>
            <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
          </td>
          <td>
            <asp:Label ID="EmailAddressLabel" runat="server" 
              Text='<%# Eval("EmailAddress") %>' />
          </td>
        </tr>
      </ItemTemplate>
      <AlternatingItemTemplate>
        <tr style="background-color: #FAFAD2;color: #284775;">
          <td>
            <asp:Label ID="ContactIDLabel" runat="server" Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
          </td>
          <td>
            <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
          </td>
          <td>
            <asp:Label ID="EmailAddressLabel" runat="server" 
              Text='<%# Eval("EmailAddress") %>' />
          </td>
        </tr>
      </AlternatingItemTemplate>
      <EmptyDataTemplate>
        <table runat="server" 
          style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;">
          <tr>
            <td>
              No data was returned.</td>
          </tr>
        </table>
      </EmptyDataTemplate>
      <InsertItemTemplate>
        <tr style="">
          <td>
            <asp:Button ID="InsertButton" runat="server" CommandName="Insert" 
              Text="Insert" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" 
              Text="Clear" />
          </td>
          <td>
            &nbsp;</td>
          <td>
            <asp:TextBox ID="FirstNameTextBox" runat="server" 
              Text='<%# Bind("FirstName") %>' />
          </td>
          <td>
            <asp:TextBox ID="LastNameTextBox" runat="server" 
              Text='<%# Bind("LastName") %>' />
          </td>
          <td>
            <asp:TextBox ID="EmailAddressTextBox" runat="server" 
              Text='<%# Bind("EmailAddress") %>' />
          </td>
        </tr>
      </InsertItemTemplate>
      <LayoutTemplate>
        <table runat="server">
          <tr runat="server">
            <td runat="server">
              <table ID="itemPlaceholderContainer" runat="server" border="1" 
                style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
                <tr runat="server" style="background-color: #FFFBD6;color: #333333;">
                  <th runat="server">
                    ContactID</th>
                  <th runat="server">
                    FirstName</th>
                  <th runat="server">
                    LastName</th>
                  <th runat="server">
                    EmailAddress</th>
                </tr>
                <tr ID="itemPlaceholder" runat="server">
                </tr>
              </table>
            </td>
          </tr>
          <tr runat="server">
            <td runat="server" 
              style="text-align: center;background-color: #FFCC66;font-family: Verdana, Arial, Helvetica, sans-serif;color: #333333;">
                <asp:Button ID="Button1" runat="server" Text="Sort by First Name" CommandName="Sort" CommandArgument="FirstName" />
                <asp:Button ID="Button2" runat="server" Text="Sort by Last Name" CommandName="Sort" CommandArgument="LastName" />
              <asp:DataPager ID="DataPager1" runat="server">
                <Fields>
                  <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" 
                    ShowLastPageButton="True" />
                </Fields>
              </asp:DataPager>
            </td>
          </tr>
        </table>
      </LayoutTemplate>
      <EditItemTemplate>
        <tr style="background-color: #FFCC66;color: #000080;">
          <td>
            <asp:Button ID="UpdateButton" runat="server" CommandName="Update" 
              Text="Update" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" 
              Text="Cancel" />
          </td>
          <td>
            <asp:Label ID="ContactIDLabel1" runat="server" 
              Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:TextBox ID="FirstNameTextBox" runat="server" 
              Text='<%# Bind("FirstName") %>' />
          </td>
          <td>
            <asp:TextBox ID="LastNameTextBox" runat="server" 
              Text='<%# Bind("LastName") %>' />
          </td>
          <td>
            <asp:TextBox ID="EmailAddressTextBox" runat="server" 
              Text='<%# Bind("EmailAddress") %>' />
          </td>
        </tr>
      </EditItemTemplate>
      <SelectedItemTemplate>
        <tr style="background-color: #FFCC66;font-weight: bold;color: #000080;">
          <td>
            <asp:Label ID="ContactIDLabel" runat="server" Text='<%# Eval("ContactID") %>' />
          </td>
          <td>
            <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
          </td>
          <td>
            <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
          </td>
          <td>
            <asp:Label ID="EmailAddressLabel" runat="server" 
              Text='<%# Eval("EmailAddress") %>' />
          </td>
        </tr>
      </SelectedItemTemplate>
    </asp:ListView>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
      ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
      SelectCommand="SELECT  ContactID, FirstName, LastName, EmailAddress FROM Person.Contact">
    </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>

Next Steps

This walkthrough has shown you the basic steps for using a ListView control to display, page, and sort data records by using one of the layouts provided for the control. You might want to experiment with additional features of the ListView control and explore different scenarios. For example, you might want to edit, delete, and insert records. For more information, see Walkthrough: Modifying Data Using the ListView Web Server Control.

See Also

Tasks

How To: Secure Connection Strings when Using Data Source Controls

Walkthrough: Basic Data Access in Web Pages

Concepts

ListView Web Server Control Overview