DataList and Repeater data paging

Source: Internet
Author: User

Paging and sorting are features that are often used when displaying data. For example, when searching for a book about ASP. NET in an online bookstore, it may result in hundreds of thousands, and only 10 per page. The results can be sorted by title (title), Price, page count (page), author name (author), and so on. As we have already discussed in pagination and sorted report data, the GridView, DetailsView, and FormView have built-in paging capabilities that can be opened only by ticking a checkbox. The GridView also supports built-in sorting.

Unfortunately, neither DataList nor repeater provide built-in paging and sorting capabilities. In this chapter we will learn how to add pagination and sorting support in DataList and Repeater. We need to create a paging interface, display the correct page records, and make a note of the page you browsed during the postback process. While this will take more time and write more code than the GridView, DetailsView, and FormView, it also provides more extensibility.

Note: This chapter focuses on paging, and we'll learn about sorting in the next chapter.

First step: Add pagination and Sort Tutorials page

First add the pages that are required for this chapter and the next chapter. Create a folder named Pagingsortingdatalistrepeater, and then add the following 5 pages, and remember to select all Site.master.


Figure 1: Creating a page

Then open the Default.aspx page and drag a Sectionleveltutoriallisting.ascx user control in from the UserControls folder. We've used this user control a lot of times. See the Master Board page and site navigation.

Figure 2: Adding a User control

In order to list the sort and pagination tutorials, we need to add them to the site map. Open the Web.sitemap file and add the following markup language to the node behind Editing and Deleting with the DataList ():

<sitemapnode url= "~/pagingsortingdatalistrepeater/default.aspx" title= "Paging and sorting with the DataList and Repeater "description=" Paging and sorting the Data in the DataList and Repeater Controls "> <sitemapnode url=" ~/pagi Ngsortingdatalistrepeater/paging.aspx "title=" Paging "description=" learn how to page through the data shown in the DataList and Repeater controls. "/> <sitemapnode url=" ~/pagingsortingdatalistrepeater/sorting.aspx "title=" Sorting "description=" Sort the data displayed in a DataList or Repeater control. "/> <sitemapnode url=" ~/pagi Ngsortingdatalistrepeater/sortingwithdefaultpaging.aspx "title=" sorting with Default Paging "description=" Create A DataList or Repeater control, which is paged using the default paging and can be sorted. "/> <sitemapnode url=" ~/pag Ingsortingdatalistrepeater/sortingwithcustompaging.aspx "title=" sorting with Custom Paging "description=" Learn     Sort the data displayed in a DataList or Repeater control that uses custom paging. "/></sitemapnode> 

Figure 3: Update Site Map

Look back at the page break

In front of us we learned how to use the GridView, DetailsView, FormView to page. All three of these controls provide a feature called default paging, simply by ticking "enable Paging" from the smart tag (to turn on paging). When using the default paging, data is requested every time-whether it is the first page or another page –gridview, DetailsView, and the FormView will request all data again. The data for a particular page is then displayed based on the requested page index and the number of records displayed per page, ignoring other data (that is, data that is requested but not displayed). We have discussed the default paging in detail in the paging and sorting report data.

The default paging is not appropriate in the case of large data volumes because it requests all of the data each time. For example, imagine showing 10 data per page, with a total of 50,000. Each time a user browses a page, 50,000 data is requested from the database, and only 10 of them are displayed.

Custom paging resolves performance issues with default paging by returning only the requested data at a time. When using custom paging, we need to write a valid SQL statement that returns the correct record. We learned to use SQL Server2005 's row_number () keyword to create such a statement.

Using the default paging in DataList or Repeater, we can use the PagedDataSource class to wrap the content that needs to be paged in the productsdatatable. The PagedDataSource class has a DataSource property that can be assigned to any enum type object, and PageSize (the number of records displayed per page) and CurrentPageIndex (the index of the current page). Once these properties are set, PagedDataSource can be used as the data source for any data control. PagedDataSource returns the appropriate records according to PageSize and CurrentPageIndex. Figure 4 depicts the functionality of the PagedDataSource class.

Figure 4:pageddatasource wrapping an enumeration object with a paginated interface

PagedDataSource objects can be created and configured directly in the BLL and bound to DataList or repeater via ObjectDataSource. Or you can do this directly in the background code of the ASP. If we use the latter method, we cannot use ObjectDataSource and should directly program the paging data to DataList or repeater.

The PagedDataSource object also has attributes that support custom paging. But here we will not discuss it, because we already have in the PRODUCTSBLL Class A way to accurately return records that need to be displayed. In this chapter we will learn how to implement the default paging by adding a method to return the appropriate PagedDataSource object in the Productsbll class. We'll discuss custom paging in the next chapter.

Step Two: Add the default paging method in the BLL

The PRODUCTSBLL class now has a method that returns all product –getproducts () – and a method –getproductspaged (startrowindex,maximumrows) that returns a specific subset. When using the default paging, GridView, DetailsView, FormView uses the GetProducts () method to get all the product, but internally uses the PagedDataSource to display the correct subset of records. By implementing the same functionality in DataList and Repeater, we can create a way to simulate this behavior in the BLL.

In Productsbll, add a method with two integer parameters named Getproductsaspageddatasource:

pageindex– the index of the page displayed, starting with 0
pagesize– the number of records displayed per page.

Getproductsaspageddatasource first gets all the records from GetProducts (). Then create a PagedDataSource object that sets the CurrentPageIndex and PageSize properties to the arguments passed in, pageindex, and pagesize. The end of the method returns the configured PagedDataSource.

[System.ComponentModel.DataObjectMethodAttribute (System.ComponentModel.DataObjectMethodType.Select, false)] Public PagedDataSource getproductsaspageddatasource (int pageIndex, int. pageSize) {//Get all of the products Ductsdatatable products = getproducts (); Limit the results through a pageddatasource pageddatasource pageddata = new PagedDataSource (); Pageddata.datasource = products. Rows; Pageddata.allowpaging = true; Pageddata.currentpageindex = PageIndex; Pageddata.pagesize = PageSize; return pageddata;}

Step three: Use default paging in DataList to display product

After the Getproductsaspageddatasource method is complete, we will now create a DataList or repeater that provides the default paging. Open the Paging.aspx page under the Pagingsortingdatalistrepeater folder, drag a DataList in, and set the ID to productsdefaultpaging. Create a ObjectDataSource named Productsdefaultpagingdatasource with smart tags and configure it with the Getproductsaspageddatasource method.

Figure 5: Create and configure ObjectDataSource

Select "(None)" In the drop-down list of the update, INSERT, DELETE tag.

Figure 6: Next Larry in Update, INSERT, DELETE tag Select "(None)"

Because the Getproductsaspageddatasource method requires two parameters, the wizard prompts us to select a parameter source. The value of page index and page size must be noted during the postback process. They can exist in the view state,querystring,session or in other techniques to record them. In this chapter we use QueryString.

Use the QueryString field "PageIndex" and "pageSize" respectively to configure PageIndex and pageSize. See Figure 7. Since the user first browses the page without QueryString, you also need to set the default values for both parameters. Set the default value of pageindex to 0 (indicating that the first page of data is displayed), and set the default value of PageSize to 4.

Figure 7: Configuration parameters

When you finish configuring ObjectDataSource, Visual Studio automatically creates a ItemTemplate for DataList. Modify it so that it shows only the name,category and supplier of the product. Set the RepeatColumns property of DataList to 2,width to "100%" and the width of ItemStyle to "50%". Such a setting provides the same spacing for both columns. The markup language for DataList and ObjectDataSource should look like this after completing these:

<asp:datalist id= "productsdefaultpaging" runat= "Server" width= "100%" datakeyfield= "ProductID" datasourceid= " Productsdefaultpagingdatasource "repeatcolumns=" 2 "enableviewstate=" False "> <ItemTemplate> 

Note: Since we do not implement any update or delete functionality here, you can disable the DataList view state to reduce the size of the page.

The first time you browse the page, the values for pageindex and pagesize are not available in QueryString, so the default of 0 and 4 will be used. See Figure 8. DataList will display 4 product records.

Figure 8: Displaying 4 product

Because there is no paging interface, users cannot navigate directly to the second page at this time. We will create a paging interface in step fourth. Now we can only specify the paging parameters directly in the QueryString page. For example, we can change the address from paging.aspx to paging.aspx?pageindex=2 and then enter to browse the second page. This allows you to see the second page of data, as shown in Figure 9.

Figure 9: Displaying the second page of data

Fourth step: Create a paging interface

There are many different ways to complete the paging interface. The GridView, DetailsView, FormView provides 4 different interfaces:

Next, Previous (next page, previous page) – Users can browse to the previous page or the next page.
Next, Previous, first (page one), last (Final page) – In addition to the above features, this includes the first and last pages.
Numeric (digital) – pages are listed on the paging interface, and users can choose one page at random.
Numeric, first, last– on the basis of the previous feature, add the page one and the last page.

For DataList and Repeater, we need to decide on the paging interface and implement it. This includes pages that need to create Web controls and display requests when a button for a particular page is clicked. In addition, some control of the paging interface may need to be disabled. For example, when you use the next, Previous, first, last mode to display, if you are browsing the data on page one, then the button on the first page and the previous page should be disabled.

In this chapter we use Next, Previous, first, last interface. Add 4 buttons and set the IDs to Firstpage,prevpage,nextpage and LastPage, respectively. Set text to "<< first", "< Prev", "Next >", "Last >>".

<asp:button runat= "Server" id= "FirstPage" text= "<< first"/><asp:button runat= "Server" id= "PrevPage" Text= "< Prev"/><asp:button runat= "Server" id= "NextPage" text= "Next >"/><asp:button runat= "Server" Id= "LastPage" text= "Last >>"/>

Then create a click event handler for each button. We'll add code to display the requested page.

Make a note of the total number of records on a page

Regardless of which paging interface you choose, we need to calculate and write down the total number of records for the page. The total number of rows (and page size) determines the total page count, which determines which of the paging interface controls need to be added or enabled. In the next, Previous, first, last interface we created, page count (pages) needs to be used in two cases:

Determine if we are browsing the final page, in which case next and last buttons need to be disabled.
If the user points to the last button we need to go to the final page, whose index equals page count minus 1.

Page count is calculated by dividing the total row count by the page size (number of pages). For example, we want to page 79 records, each page shows 4, then page count is 20 (79/4). If we use the digital paging interface, this information can be used to determine how many digital page buttons to display. If the paging interface contains only next and Last buttons, you can use page count to disable Next and Last buttons.

If the paging interface contains the last button (the final page), we need to write down the total number of pages in the postback process so that we can get the index of the last page at the end of the button. To facilitate this, we create a Totalrowcount property in the backend code of the ASP to save this value in the view state.

private int totalrowcount{get {  object o = viewstate["Totalrowcount"];  if (o = = null)   return-1;  else   return (int) o;} set {  viewstate["totalrowcount"] = value;}}

In addition to Totalrowcount, it is also necessary to create page-level read-only properties for pages index,page size and page count to facilitate reading.

private int pageindex{get {  if (!string. IsNullOrEmpty (request.querystring["PageIndex"))   return Convert.ToInt32 (request.querystring["PageIndex"]);  else   return 0;}} private int pagesize{get {  if (!string. IsNullOrEmpty (request.querystring["PageSize"))   return Convert.ToInt32 (request.querystring["pageSize"]);  else   return 4;}} private int pagecount{get {  if (totalrowcount <= 0 | | PageSize <= 0)   return 1;  else   return ((Totalrowcount + PageSize)-1)/PageSize;}}

Get total number of records for pagination

The Select () method from ObjectDataSource returns a PagedDataSource object that contains all the product records, even if only a subset is displayed in DataList. The Count property of PagedDataSource returns the number of items that will be displayed in the DataList. Datasourcecount property returns the total number of all items in the PagedDataSource. So we need to assign the Totalrowcount property of the ASP to the PagedDataSource Datasourcecount.

We created an event handler for ObjectDataSource's SELECTD event to do this. In SELECTD's event handler we get the return value of the ObjectDataSource Select () method – in this case it is pageddatasource.

protected void productsdefaultpagingdatasource_selected (object sender, ObjectDataSourceStatusEventArgs e) {// Reference the PagedDataSource bound to the DataList pageddatasource pageddata = (pageddatasource) e.returnvalue; Remember the total number of records being paged through//across postbacks Totalrowcount = Pageddata.datasourcecount; }

Display data for the requested page

When the user points to a button on the paging interface, we need to display the data for the requested page. Because the paging parameter is specified in QueryString, the Response.Redirect (URL) is used to allow the user to request a paging.aspx page with the appropriate paging parameters. For example, the second page of data is displayed, and we redirect the user to Paging.aspx?pageindex=1.

Create a Redirectuser (Sendusertopageindex) method to redirect the user to Paging.aspx?pageindex=sendusertopageindex. This method is then called in the Click event Handling of the four buttons. Call Redirectuser (0) in Firstpageclick and call Redirectuser (PageIndex-1) in Prevpageclick.

protected void Firstpage_click (object sender, EventArgs e) {//Send the user to the first page redirectuser (0);} protected void Prevpage_click (object sender, EventArgs e) {//Send the user to the previous page Redirectuser (PageIndex- 1);} protected void Nextpage_click (object sender, EventArgs e) {//Send the user to the next page redirectuser (PageIndex + 1);} protected void Lastpage_click (object sender, EventArgs e) {//Send the user to the last page Redirectuser (PageCount-1);} private void Redirectuser (int sendusertopageindex) {//Send the user to the requested page Response.Redirect (string. Format ("Paging.aspx?pageindex={0}&pagesize={1}",  Sendusertopageindex, pageSize));}

Once the Click event has been processed, DataList's records can now be paged through the button, which you can test.

Disable Paging control

Now no matter which page you browse, four buttons are available. However, we need to disable first and previous buttons when we navigate to page one, and we need to disable Next and last buttons when we browse the final page. The PagedDataSource object returned by the ObjectDataSource Select () method has several properties –isfirstpage and islastpage– can determine whether the user is browsing the first or last page of data through them. Add the following code to ObjectDataSource's selected event handler:

Configure the paging interface based on the data in the pageddatasourcefirstpage.enabled =!pageddata.isfirstpage; prevpage.enabled =!pageddata.isfirstpage; nextpage.enabled =!pageddata.islastpage; lastpage.enabled =!pageddata.islastpage;

When you are finished adding, first and previous buttons will be disabled when you browse to page one. Next and Last buttons will be disabled when the final page is browsed.

We finally implemented a paging interface that informs users which page they are currently viewing and how many pages they have. Add a Label control and set the ID to Currentpagenumber. In ObjectDataSource's selected event handling, set its Text property to display the currently browsed page (PAGEINDEX+1) and the total number of pages (PageCount).

Display the current page being viewed ... Currentpagenumber.text = string. Format ("You are viewing page {0} of {1} ...", PageIndex + 1, PageCount);

Figure 10 is the first time you look at a paging.aspx page. Because QueryString is empty, the DataList default displays the first 4 product. First and previous buttons are disabled. Click Next to display the following 4 records (see Figure 11), while first and previous buttons are also enabled.

Figure 10: first page data

Figure 11: The second page of data

Note: The paging interface can be further improved, such as allowing users to specify how many records to display per page. For example, add a DropDownList that lists the options for page size, such as 5, 10, 25, 50, and all. When the user selects the page size, it is redirected to Paging.aspx?pageindex=0&pagesize=selectedpagesize. I leave this as an exercise for the reader to complete.

Using a custom page-out

DataList uses the inefficient default paging technology. When it comes to large data volumes, we need to use custom paging. Although the details of the implementation are different, the concept in pagination is the same as the default paging. When paging by default, use the Getproductspaged method of the Productsbll class instead of Getproductsaspageddatasource. As discussed in improving the efficiency of paging in large data volumes, the getproductspaged needs to pass in the index of the start row and the maximum number of rows. These parameters can be saved by using the pageindex and pagesize parameters in the querystring used in the default paging.

Since there is no pageddatasource in the custom paging, other techniques are needed to determine the total number of records and to determine whether we are displaying the first or last page of data. The Totalnumberofproducts () method of the Productsbll class returns the total number of records for roduct. To determine if the first page of data is being browsed, we need to check the index of the start row-if it is 0, the first page is browsed. If the index of the start row plus the maximum number of rows is greater than or equal to the total number of records is represented on the last page. We will discuss in detail how to implement custom paging in the next chapter.


DataList and repeater do not provide paging support like the GridView, DetailsView, and FormView, and such features need to be implemented by us. The simplest way to do this is to use the default paging, wrap all the product into PagedDataSource, and then bind PagedDataSource to DataList or repeater. In this chapter we add the Getproductsaspageddatasource method to the PRODUCTSBLL class, which returns PagedDataSource. The PRODUCTSBLL class already contains the methods –getproductspaged and totalnumberofproducts required for custom paging.

We need to manually add a paging interface, whether it's getting accurate records in a custom method or getting all the records in the default method. In this chapter we create next, Previous, first, last interface with 4 button controls. Of course, a label control is added that displays the current page and the total number of pages.

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