Manipulating data in ASP.net 2.0 24: Paging and Sorting report data _ self-study process

Source: Internet
Author: User
Tags class definition code tag

Introduction

Paging and sorting is a common feature of presenting data in a Web application. For example, when we search for ASP.net books in an online bookstore, there may be hundreds of related books, but we only want to display 10 valid records per page. Also, we want the results to be sorted by title, price, page number, author, and so on. In the past 23 tutorials, we've studied how to build various reports, including adding edits and deleting data to the interface. But we're not looking at how to sort the data, and we're only looking at the DetailsView and FormView controls when we look at pagination.

Step 1: Add pagination and sort pages

Before we begin, let's take the time to add the pages that need to be used in the last four tutorials, including this article. Let's start by creating a new folder called PagingAndSorting in the project, and next, add the following pages to the directory and configure to use the Site.master master page.

Default.aspx
Simplepagingsorting.aspx
Efficientpaging.aspx
Sortparameter.aspx
Customsortingui.aspx

Figure 1: Creating a pagingandsorting folder and adding a tutorial page

Next, let's open the Default.aspx page and drag the Sectionleveltutoriallisting.ascx user control from the UserControls to the design interface. The user control we created in the master page and the site navigation tutorial traverses the site map and renders them in a symbolic list.

Figure 2: Adding the Sectionleveltutoriallisting.ascx user control to the Default.aspx

To show us the pagination and sorting tutorials we are going to create, we need to add them to the Sitemap. Open the Web.sitemap file and add the following code after the edit, insert, and delete SiteMapNode tag:

<sitemapnode title= "Paging and Sorting" url= "~/pagingandsorting/default.aspx" description= "The Samples of Reports that P Rovide paging and sorting capabilities "> <sitemapnode url=" ~/pagingandsorting/simplepagingsorting.aspx "title= "Simple Paging & Sorting examples" Description= "examines you to add simple paging and sorting support."/> &L T;sitemapnode url= "~/pagingandsorting/efficientpaging.aspx" title= "efficiently paging Through Large result Sets" D Escription= "Learn to efficiently page through large result sets/>" <sitemapnode Parameter.aspx "title=" sorting Data at the BLL or DAL "description=" illustrates how to perform sorting logic in th
    E Business Logic Layer or Data Access Layer. "/> <sitemapnode url=" ~/pagingandsorting/customsortingui.aspx " Title= "Customizing the Sorting User Interface" description= "Learn how to customize and improve the sorting User inte Rface. "/> </sitemApnode>

 

Figure 3: Update the site map to include the new page

Step 2: Display product information in the GridView

Before we really implement paging and sorting, let's start by creating a standard GridView that does not have sorting and paging capabilities to display product information. In fact, we have done this work many times, we should be very familiar with. First open the Simplepagingsorting.aspx page and drag a GridView control from the Toolbox to the designer, and configure its ID attribute to products. Next, create a new ObjectDataSource and use the GetProducts () method of the Productsbll class to get all the product information.

Figure 4: Obtaining all product information using the GetProducts () method

Since this report is read-only, we do not need to map the ObjectDataSource INSERT (), update (), and Delete () methods to the corresponding PRODUCTSBLL method, so for Update, INSERT, and Delete Page We selected (None) from the Drop-down list.

Figure 5: For the update, INSERT, and delete pages, we select the (None) option from the Drop-down list

Next, let's adjust the GridView field so that it displays only the product name, vendor, category, Price, and status. In addition, we can make some formatting adjustments, such as configuring the price of HeaderText to match our monetary form. After these modifications, our GridView code should be similar to the following:

<asp:gridview id= "Products" runat= "server" autogeneratecolumns= "False"
  datakeynames= "ProductID" Datasourceid= "ObjectDataSource1"
  enableviewstate= "False" >
  <Columns>
    <asp:boundfield Datafield= "ProductName" headertext= "Product"
      sortexpression= "ProductName"/>
    <asp:boundfield Datafield= "CategoryName" headertext= "Category"
      readonly= "True" sortexpression= "CategoryName"/>
    < Asp:boundfield datafield= "SupplierName" headertext= "Supplier" readonly= "
      True" sortexpression= "SupplierName"/ >
    <asp:boundfield datafield= "UnitPrice" headertext= "Price"
      sortexpression= "UnitPrice" Dataformatstring= ' {0:c} '
      htmlencode= ' False '/>
    <asp:checkboxfield datafield= ' discontinued ' headertext= "discontinued"
      sortexpression= "discontinued"/>
  </Columns>
</asp:gridview >

Figure 6 shows the effect in the browser, but notice that we display the product on a screen. Displays the name, category, vendor, Price, and status of each product.

Figure 6: Each product is listed.

Step 3: Add paging support

Listing all the products on one screen is inconvenient for the user to view the data. To make the results more manageable, we should present the data in several pages and provide users with the ability to switch pages. To do this you only need to select the Paging check box before the GridView Smart tag (in fact, set the AllowPaging property to True).

Figure 7: Click the Enable paging check box to support paging

When paging is turned on, the number of records displayed per page is limited and paging navigation is added to the GridView. The default, as shown in Figure 7, is a series of pages of numbers that run the user quickly from one page to another. In fact, we are not unfamiliar, in the past tutorial we have for the DetailsView FormView control to provide excessive page support.

The DetailsView and FormView controls only support displaying a single record per page. But for the GridView, there is a pagesize property that lets us configure the number of records to display per page (the default is set to 10).

GridView, DetailsView and FormView paging navigation can be configured using the following properties:

pagerstyle– indicates the style of paging navigation, can set BackColor, ForeColor, CssClass, HorizontalAlign, and so on.
pagersettings– contains a number of properties that customize the paging navigation functionality; Pagebuttoncount represents the maximum number of pages (by default) that displays navigation at the bottom part of the page; The Mode property represents the form of a paging operation and can be set to:
nextprevious– displays the next and previous buttons, allowing the user to turn back or forward one page at a time
nextpreviousfirstlast– In addition to the next and previous buttons, also provides the first and last buttons, so that users can quickly navigate to the home page or last page data
numeric– displays a series of page numbers, allowing the user to click the number directly to switch to the corresponding page
numericfirstlast– In addition to the page number also provides the first and last page buttons, so that users can quickly navigate to the home page or last data, only when there is no home page or last number display button

In addition, the GridView, DetailsView, and FormView also provide the pageindex and PageCount properties to indicate the total number of pages and pages currently rendered. The PageIndex property is numbered from 0, so when we browse the first page it is 0, and PageCount is numbered from 1, so the pageindex range is between 0 and pagecount–1.

Let's take some time to improve the default appearance of the GridView Pager. First, we navigate the pagination to the right and set it to the gray background color. Instead of setting the PagerStyle property of the GridView directly, we create a CSS class called Pagerrowstyle in Styles.css and then associate the CssClass property of the PagerStyle in the theme file. First open Styles.css and then add the following CSS class definition to the file:

. Pagerrowstyle
{
  background-color: #ddd;
  Text-align:right;
}

Next, open the Gridview.skin file in the DataWebControls folder in the App_Themes folder. As we mentioned in the motherboard page and in the site navigation tutorial, the skin file can specify a default property value for the Web control. Therefore, we set the PagerStyle CssClass property to Pagerrowstyle. Again, let's configure pager to display 5 page numbers (numericfirstlast mode).

<asp:gridview runat= "Server" cssclass= "Datawebcontrolstyle" >
  <alternatingrowstyle cssclass= " AlternatingRowStyle "/>
  <rowstyle cssclass=" RowStyle "/>  
 

Pagination User Experience

We have enabled pagination for the GridView and configured PagerStyle and pagersettings in the Gridview.skin file, Figure 8 shows the rendering in the browser. Note that there are only 10 records per page, and from the pager we can know that we are browsing the first page of data.

Figure 8: Displaying only one part of a record at a time after paging is enabled

When the user clicks a page number in the pager, the page is sent back and the data for the requested page is rendered. Figure 9 shows the effect of clicking on the last page. Note that the last page has only one record, because there are 81 records, each page shows 10 records, 8 pages 80, the last page is left.

Figure 9: Click a page Digital page postback to display a corresponding set of records

How the paging service side works

When the user clicks the button in the pager, the page sends back and starts the following service-side workflow:

1.GridView (or DetailsView or FormView) pageindexchanging time Trigger

2.ObjectDataSource obtains all data from BLL; the pageindex and PageSize properties of the GridView are used to detect which data obtained from BLL needs to be displayed on the page

3.GridView pageindexchanged Event Trigger

In the second step, ObjectDataSource gets all the data from the data source. If we just set the AllowPaging property to True to page pagination, the default way of paging the Web control is to get all the data and pick the appropriate HTML rendering on the browser. Caching data in a database by BLL or ObjectDataSource is inefficient for systems with large data volumes or for large concurrent applications.

In the next tutorial, we'll look at how to implement custom paging. Using custom Paging we can instruct ObjectDataSource to get exactly the data that the user requested. You can imagine that for a recordset with large data, custom paging can greatly increase efficiency.

  Note: The default paging is not suitable for large data collection systems and large traffic concurrency situations, custom paging can improve but it does require a lot of changes to implement (rather than simply selecting a check box as the default paging). As a result, the default paging is appropriate for small, small-volume Web sites because the implementation is really simple and fast.

For example, if we are sure that there are no more than 100 products in the database. If we use custom paging, it's not worth the time you spend and the efficiency you win. However, if I have thousands of tens of thousands of of products, not implementing custom paging will greatly reduce the performance of our applications.

Step 4: Customizing the Paging Experience

Data Web controls provide some properties to enhance the paging experience. For example, the PageCount property indicates how many pages are in total, the PageIndex property indicates the currently visited page, and can be set to quickly navigate to a page. To demonstrate how to use these properties to enhance the user paging experience, let's add a label Web control on the page to display the page that the user is currently visiting, and add a DropDownList control to let the user quickly switch to a page.

First, add a label Web control to the page, set its id attribute to paginginformation, and then empty the text. Next, create an event handler for the DataBound event for the GridView, and then add the following code:

protected void Products_databound (object sender, EventArgs e)
{
  Paginginformation.text = string. Format ("You are viewing page {0} of {1} ...",
    Products.pageindex + 1, products.pagecount);
}

This event handler specifies the Paginginformation label's Text property for the user's currently visited page-products.pageindex + 1 (we are here + 1 because the Products.pageindex property is numbered from 0) and the total number of pages (Products.pagecount). The reason I do this in the DataBound event handler instead of the PageIndexChanged event handler is that the DataBound event is triggered every time the data is bound to the GridView. The pageindexchanged only triggers when the page is switched. When the GridView binds the home page, Pageindexchanging has not yet been triggered (and the DataBound event can be triggered).

Well, users can now see the total number of pages and pages they are accessing.

Figure 10: Displaying the total number of current pages and pages

In addition to the label control, we add a DropDownList control to display all the pages and select the currently browsed page. In this way, the user can select an option in DropDownList to quickly switch to the new page index, we first drag a DropDownList to the designer, then set the ID property to PageList and then select Enable AutoPostBack.

Next, add the following code to the databound:

Clear out all of the items in the DropDownList
PageList.Items.Clear ();
Add a ListItem for each page for
(int i = 0; i < Products.pagecount; i++)
{
  //ADD the new ListItem
  ListItem Pagelistitem = new ListItem (string. Concat ("Page", I + 1), i.tostring ());
  PAGELIST.ITEMS.ADD (Pagelistitem);
  Select the current item, if needed
  if (i = = products.pageindex)
    pagelistitem.selected = true;
}

This code first clearly pagelist all the items in the DropDownList. Since we cannot anticipate that the number of pages will not change, it seems that this operation may be superfluous. However, other users may use the system to add or remove records from the Products table concurrently. Such an INSERT or delete operation may change the number of pages in the data.

Next, we re-create the number of pages and select the GridView pageindex as the default. We loop 0 to pagecount–1 to add every listitem, and if the current loop is equal to the pageindex attribute of the GridView, we set the selected property of this item to true.

Finally, we need to create an event handler for the DropDownList SelectedIndexChanged event. When a user chooses a different page to trigger each time, we only need to double-click the DropDownList in the designer to create the event handler, and then add the following code:

protected void Pagelist_selectedindexchanged (object sender, EventArgs e)
{
  //Jump to the specified page
  Products.pageindex = Convert.ToInt32 (Pagelist.selectedvalue);
}

As shown in Figure 11, it is simply to change the PageIndex property of the GridView and rebind the GridView. In the DataBound event handler for the GridView, the corresponding DropDownList ListItem is selected.

Figure 11: The user chooses the Drop-down List page 6 to switch to page sixth

Step 5: Add bidirectional sort support

Adding support for bidirectional sorting is as simple as adding paging support-You only need to select the Enable sorting option for the GridView Smart Tag (it sets the GridView AllowSorting property to True). In this way, the title of each field in the GridView will be displayed as LinkButtons, the page will be back when clicked, and all the data in the column will be displayed in ascending order. Clicking the same LinkButton again can be shown in descending order.

  Note: If you use a custom data access layer instead of a strongly typed DataSet, you may not be able to find the GridView Enable sorting option. Because the Ado.net DataTable provides the sort method to sort the datarow of a DataTable using the specified criteria, the strongly typed DataSet provides sort support.

If your DAL does not return objects that support sorting, we need to configure ObjectDataSource to sort the return data for the business logic layer. We'll look at how to sort the business logic or data in the data access layer in a future tutorial.

The sorted LinkButton is rendered as an HTML link, and the current color (not accessed with no blue access is dark red) and the background color of the title conflict, let's set all the links in the title to be white in both the visited and the inaccessible cases. We implement this by adding the following classes to the Styles.css:

. HeaderStyle A,. HeaderStyle a:visited
{
  color:white;
}

This code indicates that all links in the HeaderStyle class are displayed in white.

After you have defined the CSS, the effect in the page browser is as shown in Figure 12, and Figure 1 shows how the link on the Price field header is clicked.

Figure 12: The results are sorted according to UnitPrice in positive order form

Research how to sort work

All the GridView fields-boundfield, CheckBoxField, TemplateField, and so on-all have sortexpression properties that indicate how the sort links on the header are sorted when clicked. The GridView also has a sortexpression attribute. When the sort LinkButton is clicked, the GridView sets its sortexpression to the sortexpression of the field, and then, The data is returned in a certain order from the ObjectDataSource, according to the SortExpression attribute of the GridView. The following is a list of the specific process steps for the GridView when ordering users:

1.GridView Sorting Event Trigger

The SortExpression property of the 2.GridView is set to click the SortExpression in the field LinkButton

3.ObjectDataSource retrieves all the data from the BLL and sorts the data according to the sortexpression of the GridView

The 4.GridView pageindex is placed 0, which means that the user is transferred to the first page of data (assuming paging is on)

5.GridView Sorted Event Trigger

As with default paging, the default sort gets all the data sorted from the BLL. Without paging or by default, we have no way to improve performance (in addition to caching data). In subsequent tutorials, however, we can make sorting more efficient by customizing pagination.

When binding a ObjectDataSource to the GridView through the Drop-down list of the GridView ' s smart tag, each GridView fie The LD automatically has its SortExpression property is assigned to the name of the ' the ' data field in the Productsrow class. For example, the ProductName BoundField ' s sortexpression are set to ProductName, as shown in the following declarative mark Up

If we bind ObjectDataSource to the GridView using the GridView smart tag drop-down box, the field of the GridView automatically sets the SortExpression property to the corresponding Productsrow class. For example, the sortexpression of ProductName BoundField is set to ProductName, the code is as follows:

<asp:boundfield datafield= "ProductName" headertext= "Product" sortexpression=
  "ProductName"/>

A field can prevent sorting by clearing the SortExpression (set to an empty string) property. Imagine if we don't want the user to sort the product by price, we can remove the UnitPrice in the code tag or in the Field dialog box (click on the GridView smart Tag's edit columns link) BoundField's SortExpression attribute example is implemented.

Figure 13: The results are sorted in ascending order according to UnitPrice

Once the SortExpression property of the UnitPrice BoundField is removed, the caption is just text instead of a link, preventing the user from ordering by price.

Figure 14: Removing the SortExpression attribute, the user can no longer sort by product price

Programmatic sort GridView

We can also use the GridView Sort method to programmatically sort the contents of the GridView. You only need to pass in SortExpression and SortDirection (ascending or descending).

We turned off the UnitPrice sort of thinking that we don't want users to buy only the cheapest things. However, we want to encourage users to buy the most expensive products, so we want to be able to sort by price but only offer a sort of order from the highest price to the lowest price.

To achieve this, we first add a button Web control to the page and set its ID property to the Sortpricedescending,text property of Sort by Price. Then in the designer double-click the button control to create the Click event handler for the button, add the following code:

protected void Sortpricedescending_click (object sender, EventArgs e)
{
  //Sort by UnitPrice in descending order
   products.sort ("UnitPrice", sortdirection.descending);
}

Click on the button page to turn to the first page and order the price, from the most expensive to the cheapest (see Figure 15).

Figure 15: Click on the button to sort the product from the most expensive to the cheapest

Summarize

In this tutorial we have said how to implement the default paging and sorting, just select a check box to achieve! There are similar ways to work when users sort or switch pages:

1. Page postback

2. Event firings for data Web control pre-level (pageindexchanging or sorting)

3. All information retrieved from ObjectDataSource

4. Event firings for data Web control post-level (pageindexchanged or Sorted)

We implemented basic paging and sorting of reports, but for better performance we also need to create custom pagination or further improve the paging and sorting interface. The following tutorial will continue to discuss related topics.

Happy programming!

About the author

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog Http://ScottOnWriting.NET.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.