Chapter 14. Using the ListView and DataPager Controls

<feature>

IN THIS CHAPTER

</feature>

In this chapter, we examine the two new databound controls introduced with the .NET Framework 3.5: the ListView and the DataPager controls. The ListView control is an extremely flexible control. You can use it in many of the same situations in which you would have used the GridView, DataList, FormView, or Repeater control in the past.

The DataPager control works with the ListView control. It enables you to add support for paging to a ListView control.

Using the ListView Control

You can think of the ListView control as a super-flexible GridView control. Like a GridView control, the ListView control can be used to display, edit, delete, select, page through, and sort database data. However, unlike the GridView, the ListView control is entirely template driven. Furthermore, unlike the GridView control, you can use the ListView control to insert new data into a database.

You also can think of the ListView control as a replacement for the DataList control. Like a DataList control, the ListView control can be used to display database records in multiple columns. For example, you can use the ListView control to render a photo gallery.

Finally, you can think of the ListView control as a super-fancy Repeater control. Like a Repeater control, the ListView control is entirely template driven. However, unlike a Repeater control, the ListView control can be used to edit, page through, and sort database data.

The ListView control supports the following templates:

  • LayoutTemplate—Used to specify the containing element for the contents of the ListView.

  • ItemTemplate—Used to format each item rendered by the ListView.

  • ItemSeparatorTemplate—Used to display content between each item rendered by the ListView.

  • GroupTemplate—Used to specify the containing element for a group of items rendered by the ListView.

  • GroupSeparatorTemplate—Used to display content between each group of items rendered by the ListView.

  • EmptyItemTemplate—Used to render content for the remaining items in a GroupTemplate.

  • EmptyDataTemplate—Used to specify content that is displayed when no items are returned from the ListView control’s data source.

  • SelectedItemTemplate—Used to specify the content displayed for the selected item in the ListView.

  • AlternatingItemTemplate—Used to render different content for alternating items in a ListView.

  • EditItemTemplate—Used to render content for editing an item in a ListView.

  • InsertItemTemplate—Used to render content for inserting a new item in a ListView.

You learn how to use these various types of templates in the following sections.

Using the LayoutTemplate and ItemTemplate

Let’s start with a simple scenario in which you might want to use the ListView control. Suppose that you have a set of database records that you want to display in a set of HTML <div> tags. The page in Listing 14.1 illustrates how you can use the LayoutTemplate and ItemTemplate templates to display the records from the Movie database table.

Example 14.1. SimpleListView.aspx

<%@ Page Language="C#" %>
<!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>Simple ListView</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ListView
            ID="lstMovies"
            DataSourceId="srcMovies"
            runat="server">
            <LayoutTemplate>
                <div style="border:dashed 1px black">
                    <asp:Placeholder
                        id="itemPlaceholder"
                        runat="server" />
                </div>
            </LayoutTemplate>
            <ItemTemplate>
                <div style="border:solid 1px black">
                <%# Eval("Title") %>
                </div>
            </ItemTemplate>
            <AlternatingItemTemplate>
                <div style="border:solid 1px black;background-color:Silver">
                <%# Eval("Title") %>
                </div>
            </AlternatingItemTemplate>
            <EmptyDataTemplate>
                No records found
            </EmptyDataTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcMovies"
            SelectCommand="SELECT Id, Title, Director FROM Movie"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />

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

The ListView control in Listing 14.1 contains five templates. First, the LayoutTemplate is used to create a single containing <div> tag for all the items rendered by the ListView. The content contained in the LayoutTemplate is rendered once and only once. In the page in Listing 14.1, the LayoutTemplate is used to display a <div> tag with a dashed border (see Figure 14.1).

Displaying database records with a ListView control.

Figure 14.1. Displaying database records with a ListView control.

The <div> tag contains a Placeholder control with an Id of itemPlaceholder. This control is never rendered to the browser. The Placeholder control gets replaced with the contents of the ItemTemplate.

Note

Technically, you are not required to use a Placeholder control with a ListView control. Instead of using a ListView control, you can use any server-side control with an Id of itemPlaceholder. However, since the control gets replaced, it makes sense to stick with using the Placeholder control.

The ItemTemplate is used to render each of the items from the data source (or every other item when an AlternatingItemTemplate is present). In Listing 14.1, the ItemTemplate is used to render a <div> tag with a solid border. A data-binding expression is used with the <div> tag to display the value of the database Title column.

The AlternatingItemTemplate is optional. If it is present, then every other item displayed by the ListView control is rendered with the AlternatingItemTemplate. In Listing 14.1, the AlternatingItemTemplate is used to give alternating items a silver background color.

Finally, the EmptyDataTemplate is used to display content when no results are retrieved from the data source. In Listing 14.1, the EmptyDataTemplate is used to display the text “No records found” when no items are returned from the data source.

You can use the ListView control to render any HTML elements you can imagine. You can use the ListView control to render bulleted lists, an HTML table, a blog tag cloud, or even the elements of a JavaScript array. For example, the page in Listing 14.2 uses a ListView control to render an HTML table.

Example 14.2. TableListView.aspx

<%@ Page Language="C#" %>
<!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>Table ListView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ListView
            ID="lstMovies"
            DataSourceId="srcMovies"
            runat="server">
            <LayoutTemplate>
                <table>
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Director</th>
                    </tr>
                </thead>
                <tbody>
                    <asp:Placeholder
                        id="itemPlaceholder"
                        runat="server" />
                </tbody>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td><%# Eval("Title") %></td>
                    <td><%# Eval("Director") %></td>
                </tr>
            </ItemTemplate>
            <EmptyDataTemplate>
                No records found
            </EmptyDataTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcMovies"
            SelectCommand="SELECT Id, Title, Director FROM Movie"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />
    </div>
    </form>
</body>
</html>

Notice that the itemPlaceholder element in Listing 14.2 is replaced with <tr> elements. The <tr> elements are rendered by the ItemTemplate (see Figure 14.2).

Displaying a table with a ListView control.

Figure 14.2. Displaying a table with a ListView control.

Using the GroupTemplate

You can use the ListView control’s GroupTemplate to group multiple items together. Grouping items is useful when you want to display items in multiple columns. For example, you might want to display a photo gallery in which three pictures are displayed per row.

The page in Listing 14.3 displays a set of photographs within a series of HTML <div> tags. A maximum of three photographs are displayed in each <div> tag (see Figure 14.3).

Displaying a photo gallery with a ListView control.

Figure 14.3. Displaying a photo gallery with a ListView control.

Example 14.3. PhotoGallery.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    void Page_Load()
    {
        List<string> photos = new List<string>();
        photos.Add( "~/Images/Ascent.jpg" );
        photos.Add( "~/Images/Autumn.jpg" );
        photos.Add( "~/Images/Azul.jpg" );
        photos.Add( "~/Images/Home.jpg" );
        photos.Add( "~/Images/Peace.jpg" );
        photos.Add( "~/Images/Stonehenge.jpg" );
        photos.Add( "~/Images/Tulips.jpg" );

        lstPhotos.DataSource = photos;
        lstPhotos.DataBind();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Photo Gallery</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:ListView
        ID="lstPhotos"
        GroupItemCount="3"
        runat="server">
        <LayoutTemplate>
            <asp:Placeholder
                id="groupPlaceholder"
                runat="server" />
        </LayoutTemplate>
        <GroupTemplate>
            <div>
            <asp:Placeholder
                id="itemPlaceholder"
                runat="server" />
            </div>
        </GroupTemplate>
        <ItemTemplate>
            <asp:Image
                id="imgPhoto"
                ImageUrl='<%# Container.DataItem %>'
                Width="200px"
                Runat="server" />
        </ItemTemplate>
    </asp:ListView>

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

In Listing 14.3, the photographs are represented with a List collection. The List is bound to the ListView programmatically in the Page_Load() method.

Notice that the ListView includes a LayoutTemplate, GroupTemplate, and ItemTemplate. In previous listings, the LayoutTemplate included an element with an ID of itemPlaceholder. In this listing, the LayoutTemplate includes an element with an ID of groupPlaceholder. The groupPlaceholder is replaced with the containers of the GroupTemplate.

The GroupTemplate includes the itemPlaceholder element. The itemPlaceholder is replaced with the contents of the ItemTemplate.

Notice that the ListView control includes a GroupItemCount attribute. This property determines the number of items displayed in a GroupTemplate before a new GroupTemplate is created.

Note

The ListView control also supports an EmptyItemTemplate that can be used to render content for the leftover items in a GroupTemplate. For example, if you set the GroupItemCount property to 3 and there are four items, then the contents of the EmptyItemTemplate are displayed for the final two items.

Selecting a Row

You can set up the ListView control so you can use it to select items. This is useful when you want to create a master/detail form.

For example, the page in Listing 14.4 contains two ListView controls. The first ListView works like a tab strip. It enables you to select a movie category. The second ListView displays a numbered list of matching movies.

Example 14.4. MasterDetail.aspx

<%@ Page Language="C#" %>
<!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>Master/Detail</title>
    <style type="text/css">

        .categoryContainer div
        {
            width: 100px;
            font-size:small;
            border: 1px solid black;
            float:left;
            padding:3px;
            margin:3px;
        }

        .categoryContainer a
        {
            text-decoration:none;
        }

        .categoryContainer div:hover
        {
            background-color:#eeeeee;
        }

        #selected
        {
            background-color:silver;
        }

    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ListView
            ID="lstMovieCategories"
            DataSourceId="srcMovieCategory"
            DataKeyNames="Id"
            runat="server">
            <LayoutTemplate>
                <div class="categoryContainer">
                <asp:PlaceHolder
                    id="itemPlaceholder"
                    Runat="server" />
                </div>
            </LayoutTemplate>
            <ItemTemplate>
                <div>
                <asp:LinkButton
                    id="lnkSelect"
                    Text='<%# Eval("Name") %>'
                    CommandName="Select"
                    Runat="server" />
                </div>
            </ItemTemplate>
            <SelectedItemTemplate>
                <div id="selected">
                <%# Eval("Name") %>
                </div>
            </SelectedItemTemplate>
        </asp:ListView>

        <br style="clear:both" /><br />

        <asp:ListView
            ID="lstMovies"
            DataSourceId="srcMovies"
            runat="server">
            <LayoutTemplate>
                <ol>
                <asp:PlaceHolder
                    id="itemPlaceholder"
                    runat="server" />
                </ol>
            </LayoutTemplate>
            <ItemTemplate>
                <li><%# Eval("Title") %></li>
            </ItemTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcMovieCategory"
            SelectCommand="SELECT Id, Name FROM MovieCategory"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />

        <asp:SqlDataSource
            id="srcMovies"
            SelectCommand="SELECT Title FROM Movie
                WHERE CategoryId=@CategoryId"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server">
            <SelectParameters>
                <asp:ControlParameter
                    Name="CategoryId"
                    ControlID="lstMovieCategories" />
            </SelectParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

The first ListView control in Listing 14.4 is used to render something resembling a tab strip (see Figure 14.4). Notice that this ListView control has its DataKeyNames property set. Setting the DataKeyNames property causes the ListView control to build a hidden collection of primary key values when the ListView is bound to its data source. Each item in the ListView is associated with an ID value.

Displaying a master/detail form with a ListView control.

Figure 14.4. Displaying a master/detail form with a ListView control.

Furthermore, notice that the ListView control includes a SelectedItemTemplate. The contents of this template are rendered for the selected item in the ListView. You select an item by clicking one of the links rendered by the ListView control’s ItemTemplate. The links are rendered with a LinkButton control. Notice that the CommandName property of the LinkButton has the value Select. This magic command name causes the ListView to change the selected item.

The second ListView control uses the first ListView control as the source value for a select parameter. When you select a new item in the first ListView control, the second ListView control displays matching movies.

Sorting Database Data

You can sort the items in a ListView control by adding one or more button controls to the ListView that have a CommandName property set to the value Sort and a CommandArgument property set to the name of a property to sort by. For example, the page in Listing 14.5 contains a ListView that renders an HTML table. You can click the column headers to sort the table by a particular column (see Figure 14.5).

Sorting data with the ListView control.

Figure 14.5. Sorting data with the ListView control.

Example 14.5. SortListView.aspx

<%@ Page Language="C#" %>
<!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>Sort ListView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ListView
            ID="lstMovies"
            DataSourceId="srcMovies"
            runat="server">
            <LayoutTemplate>
                <table>
                <thead>
                    <tr>
                        <th>
                        <asp:LinkButton
                            id="lnkTitle"
                            Text="Title"
                            CommandName="Sort"
                            CommandArgument="Title"
                            Runat="server" />
                        </th>
                        <th>
                        <asp:LinkButton
                            id="LinkButton1"
                            Text="Director"
                            CommandName="Sort"
                            CommandArgument="Director"
                            Runat="server" />
                        </th>
                    </tr>
                </thead>
                <tbody>
                <asp:Placeholder
                    id="itemPlaceholder"
                    runat="server" />
                </tbody>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td><%# Eval("Title") %></td>
                    <td><%# Eval("Director") %></td>
                </tr>
            </ItemTemplate>
            <EmptyDataTemplate>
                No records found
            </EmptyDataTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcMovies"
            SelectCommand="SELECT Id, Title, Director FROM Movie"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />
    </div>
    </form>
</body>
</html>

The two LinkButtons used for sorting the items in the ListView are contained in the LayoutTemplate. Both LinkButtons have a CommandName property set to the value Sort. The first LinkButton sorts by the Title property and the second LinkButton sorts by the Director property.

Editing Database Data

You can use the ListView control to update, delete, and insert items. The page in Listing 14.6 illustrates how you can use the ListView to modify or delete the records in the Movie database table (see Figure 14.6).

Editing database data with the ListView control.

Figure 14.6. Editing database data with the ListView control.

Example 14.6. EditListView.aspx

<%@ Page Language="C#" %>

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

    .movie
    {
       border: solid 1px black;
       padding:5px;
       margin:3px;
    }

    .edit
    {
        background-color:lightyellow;
    }

</style>

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

        <asp:ListView
            ID="lstMovies"
            DataSourceId="srcMovies"
            DataKeyNames="Id"
            runat="server">
            <LayoutTemplate>
                <asp:Placeholder
                    id="itemPlaceholder"
                    runat="server" />
            </LayoutTemplate>
            <ItemTemplate>
                <div class="movie">
                <strong><%# Eval("Title") %></strong>
                <br />
                <em>Directed by <%# Eval("Director") %></em>
                <br />
                <asp:LinkButton
                    id="lnkEdit"
                    Text="{Edit}"
                    CommandName="Edit"
                    Runat="server" />
                <asp:LinkButton
                    id="lnkDelete"
                    Text="{Delete}"
                    CommandName="Delete"
                    OnClientClick="return confirm('Delete this movie?')"
                    Runat="server" />
                </div>
            </ItemTemplate>
            <EditItemTemplate>
                <div class="movie edit">
                <asp:Label
                    id="lblTitle"
                    Text="Title:"
                    AssociatedControlID="txtTitle"
                    Runat="server" />
                <br />
                <asp:TextBox
                    id="txtTitle"
                    Text='<%# Bind("Title") %>'
                    Runat="server" />

                <br /><br />

                <asp:Label
                    id="lblDirector"
                    Text="Director:"
                    AssociatedControlID="txtDirector"
                    Runat="server" />
                <br />
                <asp:TextBox
                    id="txtDirector"
                    Text='<%# Bind("Director") %>'
                    Runat="server" />

                <br /><br />
                <asp:LinkButton
                    id="lnkUpdate"
                    Text="Save"
                    CommandName="Update"
                    Runat="server" />
                <asp:LinkButton
                    id="lnkCancel"
                    Text="Cancel"
                    CommandName="Cancel"
                    Runat="server" />
                </div>
            </EditItemTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcMovies"
            SelectCommand="SELECT Id, Title, Director FROM Movie"
            UpdateCommand="Update Movie SET Title=@Title, Director=@Director
                WHERE Id=@Id"
            DeleteCommand="Delete Movie WHERE Id=@Id"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />

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

The ListView control in Listing 14.6 has an ItemTemplate that contains two LinkButtons. The first LinkButton has a CommandName property set to the value Edit and the second LinkButton has a CommandName property set to the value Delete. When you click the first LinkButton, the ListView control’s EditItemTemplate is displayed. When you click the second LinkButton, the current database record is deleted (after you confirm that you really want to delete the movie record).

The EditItemTemplate contains a form for editing a movie record. The form contains two TextBox controls that have two-way data-binding expressions assigned to their Text properties. The form also contains two LinkButton controls. The first LinkButton control has a CommandName of Update. When you click this button, the database is updated with the form changes and the EditItemTemplate switches back to the normal ItemTemplate. If you click the Cancel button, the EditItemTemplate switches to an ItemTemplate without updating the database.

When editing with a ListView, you need to assign the primary key column names to the ListView control’s DataKeyNames property. The ListView control uses this to determine which database record to update.

Notice that all the ListView editing is driven by the following magic command names: Edit, Delete, Update, and Cancel. By setting button control CommandName properties to these magic command names, you can control how the ListView edits items.

You also can use the ListView control to insert new records into a database table. The ListView control supports an InsertItemTemplate. The page in Listing 14.7 illustrates how you can use the InsertItemTemplate to create a simple customer feedback form (see Figure 14.7).

Inserting new records with the ListView control.

Figure 14.7. Inserting new records with the ListView control.

Example 14.7. InsertListView.aspx

<%@ Page Language="C#" %>
<!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>Insert ListView</title>
    <style type="text/css">

    .comment
    {
        margin:10px;
        padding: 10px;
        border-left:solid 1px gray;
        border-bottom:solid 1px gray;
    }

    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ListView
            ID="lstFeedback"
            DataSourceId="srcFeedback"
            InsertItemPosition="FirstItem"
            runat="server">
            <LayoutTemplate>
                <asp:Placeholder
                    id="itemPlaceholder"
                    runat="server" />
            </LayoutTemplate>
            <ItemTemplate>
                <div class="comment">
                <%# Eval("Comment") %>
                </div>
            </ItemTemplate>
            <InsertItemTemplate>
                <div>
                Please enter any comments
                about our website here:
                <br />
                <asp:Label
                    id="lblComments"
                    Text="Comments:"
                    AssociatedControlID="txtComment"
                    Runat="server" />
                <br />
                <asp:TextBox
                    id="txtComment"
                    Text='<%# Bind("Comment") %>'
                    TextMode="MultiLine"
                    Columns="40"
                    Rows="3"
                    Runat="server" />
                <br />
                <asp:Button
                    id="lnkInsert"
                    Text="Add Comment"
                    CommandName="Insert"
                    Runat="server" />
                </div>
            </InsertItemTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcFeedback"
            SelectCommand="SELECT Id, Comment FROM Feedback"
            InsertCommand="INSERT Feedback (Comment) VALUES (@Comment)"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />

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

The InsertItemTemplate appears only when you set the ListView control’s InsertItemPosition property. You can set this property to the value FirstItem, LastItem, or None. In Listing 14.7, it’s set to the value FirstItem so that the insert form appears above all the current items.

The InsertItemTemplate contains a single TextBox control that has its Text property set to a data-binding expression. The template also contains a Button control that has a CommandName property set to the value Insert. When you click the button, the new item is inserted into the database.

Using the DataPager Control

The DataPager control displays a user interface for navigating through multiple pages of items. The DataPager control works with any control that supports the IPageableItemContainer interface. Unfortunately, there is currently only a single control that supports this interface: the ListView control. So this means that you can only use the DataPager with the ListView control.

The DataPager control includes the following properties:

  • PageSizeGets or sets the number of items to display at a time.

  • PagedControlIdGets or sets the control to page (the control must implement IPageableItemContainer).

  • FieldsGets the fields contained by the DataPager.

  • StartRowIndexGets the index of the first item to show.

  • MaximumRowsGets the maximum number of rows to retrieve from the data source.

  • TotalRowCountGets the total number of items available from the data source.

You set the PageSize to control the number of items to display per page. The PagerControlId property is optional. If you place the DataPager within the ListView control’s LayoutTemplate, you don’t need to set the PagerControlId property. If, on the other hand, you place the DataPager outside of the ListView control, you need to set the PagerControlId property to the ID of the ListView.

If you add a DataPager to a page and do nothing else, the DataPager won’t render anything. To display a user interface for the DataPager, you need to add one or more fields to the DataPager. The DataPager control supports the following fields:

  • NextPreviousPagerField—Used to display Next, Previous, First, and Last links.

  • NumericPagerField—Used to display Next, Previous, and page numbers links.

  • TemplatePagerField—Used to create a custom user interface for paging.

The page in Listing 14.8 demonstrates how you can use the DataPager control to page through movies displayed by a ListView control (see Figure 14.8).

Using a DataPager control with the ListView control.

Figure 14.8. Using a DataPager control with the ListView control.

Example 14.8. DataPagerListView.aspx

<%@ Page Language="C#" %>
<!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>DataPager ListView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ListView
            ID="lstMovies"
            DataSourceId="srcMovies"
            runat="server">
            <LayoutTemplate>
                <ol>
                <asp:PlaceHolder
                    id="itemPlaceholder"
                    runat="server" />
                </ol>
                <asp:DataPager
                    id="pg"
                    PageSize="2"
                    Runat="server">
                    <Fields>
                        <asp:NextPreviousPagerField
                            ShowFirstPageButton="true"
                            ShowPreviousPageButton="true"
                            ShowNextPageButton="false"
                            ShowLastPageButton="false" />
                        <asp:NumericPagerField />
                        <asp:NextPreviousPagerField
                            ShowFirstPageButton="false"
                            ShowPreviousPageButton="false"
                            ShowNextPageButton="true"
                            ShowLastPageButton="true" />
                    </Fields>
                </asp:DataPager>

            </LayoutTemplate>
            <ItemTemplate>
                <li>
                <%# Eval("Title") %>
                </li>
            </ItemTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcMovies"
            SelectCommand="SELECT Id, Title, Director FROM Movie"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />

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

The DataPager contains three fields: NextPreviousPagerField, NumericPagerField, and NextPreviousPagerField. Notice that the DataPager contains two NextPreviousPagerFields. The first one is used to display the First and Previous links, and the second one is used to display the Next and Last links.

Creating a Custom User Interface for Paging

If you need total and complete control over the paging user interface, you can use the TemplatePagerField to customize the appearance of the DataPager. The page in Listing 14.9 illustrates how you can use the TemplatePagerField.

Example 14.9. DataPagerTemplate.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void pg_PagerCommand(object sender, DataPagerCommandEventArgs e)
    {
        e.NewMaximumRows = e.Item.Pager.MaximumRows;
        switch (e.CommandName)
        {
            case "Previous":
                if (e.Item.Pager.StartRowIndex > 0)
                    e.NewStartRowIndex = e.Item.Pager.StartRowIndex - 2;
                break;

            case "Next":
                e.NewStartRowIndex = e.Item.Pager.StartRowIndex + 2;
                break;
        }
    }

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

        <asp:ListView
            ID="lstMovies"
            DataSourceId="srcMovies"
            runat="server">
            <LayoutTemplate>
                <ul>
                <asp:Placeholder
                    id="itemPlaceholder"
                    runat="server" />
                </ul>
                <asp:DataPager
                    id="pg"
                    PageSize="2"
                    Runat="server">
                    <Fields>
                        <asp:TemplatePagerField
                            OnPagerCommand="pg_PagerCommand">
                            <PagerTemplate>
                            <asp:LinkButton
                                id="lnkPrevious"
                                Text="Previous"
                                CommandName="Previous"
                                Runat="server" />
                            <asp:LinkButton
                                id="lnkNext"
                                Text="Next"
                                CommandName="Next"
                                Runat="server" />
                            </PagerTemplate>
                        </asp:TemplatePagerField>
                    </Fields>
                </asp:DataPager>

            </LayoutTemplate>
            <ItemTemplate>
                <li>
                <%# Eval("Title") %>
                </li>
            </ItemTemplate>
        </asp:ListView>

        <asp:SqlDataSource
            id="srcMovies"
            SelectCommand="SELECT Id, Title, Director FROM Movie"
            ConnectionString='<%$ ConnectionStrings:con %>'
            Runat="server" />

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

The TemplatePagerField in Listing 14.9 contains two LinkButton controls (see Figure 14.9). The first LinkButton has a CommandName set to the value Previous, and the second LinkButton control has a CommandName set to the value Next.

Creating a custom paging user interface.

Figure 14.9. Creating a custom paging user interface.

The page also contains an event handler for the TemplatePagerField’s PagerCommand event. The actual work of paging is done within this event handler. The second argument passed to the event handler is an instance of the DataPagerCommandEventArgs class. You change the current page by assigning new values to this object’s NewStartRowIndex and NewMaximumRows properties.

Data Source Paging with the DataPager Control

You can take advantage of the DataPager control when performing data source paging. The page in Listing 14.10 contains a ListView control bound to a LinqDataSource control. Because, the LinqDataSource control has its AutoPage property set to the value true, it performs paging on the database server.

Note

The LinqDataSource control and LINQ to SQL are discussed in Chapter 18. LINQ to SQL is the preferred method of data access in .NET Framework 3.5.

Example 14.10. DataPagerDataSource.aspx

<%@ Page Language="C#" Trace="true" %>
<!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>DataPager DataSource Paging</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>


    <asp:ListView
        ID="lstMovies"
        DataSourceId="srcMovies"
        runat="server">
        <LayoutTemplate>
            <ol>
            <asp:PlaceHolder
                id="itemPlaceholder"
                runat="server" />
            </ol>
            <asp:DataPager
                id="pg"
                PageSize="2"
                Runat="server">
                <Fields>
                    <asp:NumericPagerField />
                </Fields>
            </asp:DataPager>

        </LayoutTemplate>
        <ItemTemplate>
            <li>
            <%# Eval("Title") %>
            </li>
        </ItemTemplate>
    </asp:ListView>


    <asp:LinqDataSource
        id="srcMovies"
        ContextTypeName="MyDatabaseDataContext"
        TableName="Movies"
        AutoPage="true"
        Runat="server" />

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

So that you can verify that the paging is happening through the database, I’ve set the DataContext to log to ASP.NET trace. If you look at the Trace Information section at the bottom of the page, you can see the actual SQL commands executed by the LinqDataSource control (see Figure 14.10).

Performing data source paging with the DataPager control.

Figure 14.10. Performing data source paging with the DataPager control.

Summary

I’m a huge fan of the new ListView and DataPager controls. I’m constantly running into layout limitations when using the GridView control. Because the ListView is entirely template driven, it is not subject to these same limitations.

In this chapter, you learned how to use the ListView control to display, sort, edit, and insert data. You also learned how to take advantage of the DataPager control to add paging to the ListView control. You learned how to create a custom pager template and how to perform data source paging.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset