Operating data in asp.net 2.0 41: DataList and Repeater Data Paging _ self-study process

Source: Internet
Author: User
Tags bind eval prev

Introduction

Paging and sorting are features that are often used to display data. For example, when searching for books on asp.net in an online bookstore, it might result in hundreds of 10 of pages. And the results can be sorted according to title (title), Price (prices), page count (pages), author name (author), and so on. As we've discussed in pagination and sorted report data, the GridView, DetailsView, and FormView all have built-in paging capabilities that can be turned on simply by checking a checkbox. The GridView also supports built-in sorting.

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

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

Step one: Add pagination and sort the tutorial pages

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

Default.aspx
Paging.aspx
Sorting.aspx
Sortingwithdefaultpaging.aspx
Sortingwithcustompaging.aspx


Figure 1: Creating the 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 number of times. See the motherboard page and site navigation.


Figure 2: Adding a User control

To list the sorting and paging 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 the "Editing and deleting with the DataList" ():

<sitemapnode url= "~/pagingsortingdatalistrepeater/default.aspx" title= "paging and Sorting with the DataList and Repe Ater "description=" paging and sorting the Data in the DataList and Repeater Controls "> <sitemapnode url=" ~/pagin Gsortingdatalistrepeater/paging.aspx "title=" paging "description=" Learn how to page through the data shown in th e DataList and Repeater controls. "/> <sitemapnode url=" ~/pagingsortingdatalistrepeater/sorting.aspx "title=" so Rting "description=" Sort the data displayed in a DataList or Repeater control. "/> <sitemapnode url=" ~/pa Gingsortingdatalistrepeater/sortingwithdefaultpaging.aspx "title=" sorting with Default paging "description=" Create A DataList or Repeater control-is paged using default paging and can sorted. "/> <sitemapnode url=" ~/ Pagingsortingdatalistrepeater/sortingwithcustompaging.aspx "title=" sorting with Custom paging "description=" Learn How to sort the data DisplayeD in a DataList or Repeater control that uses custom paging. "/> </siteMapNode> 


Figure 3: Updating the Site Map

Review pagination

In the front we learned how to use the GridView, DetailsView, FormView to pagination. These three controls provide a feature called default paging, which only needs to be labeled "Enable paging" (open paging) from the smart tag. When you use the default paging, each request data-whether it is the first page or another page –gridview, DetailsView, and FormView will request all of the 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, while other data is ignored (that is, data that is requested but not displayed). We have discussed the default pagination in detail in pagination and sorted report data.

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

Custom paging uses only the requested data at a time, which resolves the performance issue of the default paging. When using custom paging, we need to write a valid SQL statement that returns the correct record. We learned to create such a statement using the SQL Server2005 row_number () keyword.

Using the default paging in DataList or Repeater, we can use PagedDataSource class to wrap the content that needs paging in productsdatatable. The PagedDataSource class has a DataSource property that can be assigned to any enumerated 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 BLL, and are bound to DataList or Repeater by ObjectDataSource. Or you can do this directly in the background code of the ASP.net page. If we use the latter method, we cannot use ObjectDataSource and should directly programmatically bind the paging data to DataList or repeater.

The PagedDataSource object also has properties that support custom paging. But here we will not discuss it because we already have a way to accurately return the records that need to be displayed in the Productsbll class. 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 the custom pagination in the next chapter.

Step Two: Add the default paging method to the BLL

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

Add a method with two integer parameters in the PRODUCTSBLL named Getproductsaspageddatasource:

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

Getproductsaspageddatasource first gets all the records from GetProducts (). You then create a PagedDataSource object that sets the CurrentPageIndex and PageSize properties to incoming parameters, 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
   northwind.productsdatatable 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 to display product in DataList

After completing the Getproductsaspageddatasource method, 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 with a smart tag named Productsdefaultpagingdatasource and configure it with the Getproductsaspageddatasource method.


Figure 5: Creating and configuring ObjectDataSource

In the update, INSERT, DELETE label Drop-down list, select (None).


Figure 6: Under the update, INSERT, DELETE tab, under Larry 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 in the postback process. They can be recorded in the view state,querystring,session or by other techniques. We use QueryString in this chapter.

Use the QueryString field "PageIndex" and "pageSize" respectively to configure PageIndex and pageSize. See Figure 7. Because users do not have querystring the first time they browse the page, you also need to set the default values for both parameters. Set the default value of pageindex to 0, which indicates that the first page of data is displayed, and set the default value of PageSize to 4.


Figure 7: Configuration Parameters

After ObjectDataSource is configured, Visual Studio automatically creates a ItemTemplate for DataList. Modify it so that it displays only the name,category and supplier of the product. Set the DataList RepeatColumns property to 2,width set to "100%" and the ItemStyle width to "50%". Such a setting provides the same spacing for both columns. After completing these, the markup language for DataList and ObjectDataSource should look like the following:

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

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

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


Figure 8: Show 4 product

Because there is no paging interface, users are not able to navigate directly to the second page. We will create the paging interface in step fourth. Now we can only specify pagination parameters directly in the QueryString to 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 data for the second page, as shown in Figure 9.


Figure 9: Displaying the second page of data

Step Fourth: Create a paging interface

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

Next, Previous (next page, previous page) – Users can browse the previous or next page.
Next, Previous, first (page one), last (Final page) – In addition to the above features, this also contains the first and last pages.
Numeric (digital) – Lists the pages in the paging interface and allows users to select a page at will.
Numeric, first, last– on the previous feature, adding a second page and a last page.

For DataList and Repeater, we need to determine its paging interface and implement it. This includes the page where you need to create a Web control and display the request when the button for a particular page is clicked. Other controls on the paging interface may need to be disabled. For example, when you use the pattern of next, Previous, first, and last to display, if you browse to page one, the button on the first and previous pages should be disabled.

In this chapter we use the Next, Previous, and the last interface. Add 4 button and set ID to Firstpage,prevpage,nextpage and lastpage respectively. Set text to "<< a", "< Prev", "Next >", "Last >>".

<asp:button runat= "Server" id= "FirstPage" text= "<<" "/> <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 handling for each button. Stay here. We will add code to display the requested page.

Make a note of the total number of records for paging

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

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

Page count is computed by dividing the total row count by page size (pages). For example, we want to page 79 records, 4 per page, then page count is 20 (79/4). If we use the digital paging interface, this information can be used to determine the number of button pages 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 (final page), we need to make a note of the total number of pages in the postback process, so that we can get the last page index at the end button. To facilitate this, we create a Totalrowcount attribute in the background code of the ASP.net page 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, you need to create a page-level read-only property for the 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 paging

Returns a PagedDataSource object containing all the product records from the ObjectDataSource Select () method, even if only a portion is displayed in the DataList. The PagedDataSource Count property 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.net page to the datasourcecount of PagedDataSource.

We do this by creating an event handler for the ObjectDataSource SELECTD event. In SELECTD's event handler we get the return value of the ObjectDataSource Select () Method-PagedDataSource in this case.

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.datasour Cecount;
}

Display data for the requested page

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

Create a Redirectuser (Sendusertopageindex) method to redirect users to Paging.aspx?pageindex=sendusertopageindex. This method is then invoked 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 "the" "the" the "the" the "" "
 );
}
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));
}

After you complete the Click event Processing, the DataList record can now be paged through the button, which you can test.

disabling paging controls

Now, no matter which page you browse, four buttons are available. However, we need to disable the 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 through the ObjectDataSource Select () method has several properties –isfirstpage and islastpage– that allow them to determine whether the user browses to the first or last page of data. Add the following code to the ObjectDataSource selected event handler:

Configure the paging interface based on the data in the PagedDataSource
firstpage.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 you browse the final page.

The last thing we do is to notify users in the paging interface which page they are currently browsing and how many pages there are. Add a Label control and set the ID to Currentpagenumber. Set its Text property in ObjectDataSource's selected event handler 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 to browse the Paging.aspx page. Because the querystring is empty, DataList displays the first 4 product by default. The previous buttons is disabled. Point next Displays the following 4 records (see Figure 11), while the previous buttons is also enabled.


Figure 10: first page data


Figure 11: second page data

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

Use custom Paging

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

Because there is no pageddatasource in custom paging, other techniques are required 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 roduct. In order to determine whether the first page of data is 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, it is on the last page. We will discuss in detail how to implement custom paging in the next chapter.

Summarize

DataList and repeater do not provide paging support like the GridView, DetailsView, and FormView, and this functionality needs to be implemented. The easiest 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 methods for customizing the paging needs –getproductspaged and totalnumberofproducts.

Whether you get the exact record in the custom method or the default method to get all the records, we need to add the paging interface manually. In this chapter, we create Next, Previous, first, and last interface, which contains 4 button controls. Of course, a label control that displays the current page and total number of pages is added.

The next chapter will learn how to provide sorting capabilities for DataList and repeater. We also create a DataList that supports both pagination and sorting (and examples that use default and custom pagination)

I wish you a happy programming!

Author Introduction

Scott Mitchell, author of this series of tutorials, has six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. You can click to see all Tutorials "[translation]scott Mitchell asp.net 2.0 data tutorial," I hope to learn asp.net help.

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.