Manipulating data in ASP.net 2.0 43: DataList and Repeater data Sorting (ii) _ self-study process

Source: Internet
Author: User
Tags eval

Then on the introduction, the previous article has been DropDownList simple to achieve the sort of function, let's look at the sorting with pagination how to do.

Fifth step: Add sort support for DataList with default paging

Open the Sortingwithdefaultpaging.aspx and paging.aspx pages in the Pagingsortingdatalistrepeater folder. View the source file in the Paging.aspx page. Copy the text selected in Figure 8 and paste it into the <asp:Content> tab in the Sortingwithdefaultpaging.aspx page.


Figure 8: Copy and paste code

Then paste the properties and methods in the Paging.aspx page background code into the sortingwithdefaultpaging.aspx page background code. Now browsing the Sortingwithdefaultpaging.aspx page, it should now have the same look and functionality as the Paging.aspx page.

Add default paging and sorting methods in PRODUCTSBLL

In the previous chapter we created a Getproductsaspageddatasource (PageIndex, PageSize) method in the Productsbll class, which returns a PagedDataSource object. This object obtains all the product through the BLL getproducts () method, but the DataList is only those records that are related to the input parameters pageindex and pageSize.

Earlier in this chapter we have added sorting by specifying sort expression in ObjectDataSource's selecting event handler. This method works well when ObjectDataSource returns a sortable object, such as the productsdatatable returned by the GetProducts () method. However, the PagedDataSource object returned by the Getproductsaspageddatasource method does not support sorting its internal data, so we need to getproducts () before putting the data into PagedDataSource. method to sort the records returned by the

Build a Getproductssortedaspageddatasource (SortExpression, PageIndex, PageSize) method in the Productsbll class. Specifies the sort attribute of the productsdatatable default Datatableview returned by the GetProducts () method.

[System.ComponentModel.DataObjectMethodAttribute
 (System.ComponentModel.DataObjectMethodType.Select, false)]
Public PagedDataSource Getproductssortedaspageddatasource
 (string sortexpression, int pageIndex, int pageSize) {//Get all of the products
 northwind.productsdatatable Products
 = GetProducts ();
 Sort the Products
 . Defaultview.sort = SortExpression;
 Limit the results through a pageddatasource
 pageddatasource pageddata = new PagedDataSource ();
 Pageddata.datasource = products. DefaultView;
 Pageddata.allowpaging = true;
 Pageddata.currentpageindex = PageIndex;
 Pageddata.pagesize = PageSize;
 return pageddata;
}

The Getproductssortedaspageddatasource method is a bit different from the Getproductsaspageddatasource method in the previous chapter. Getproductssortedaspageddatasource has a sortexpression parameter that assigns its value to the Productdatatable DefaultView sort property. and assigns the productdatatable DefaultView to the DataSource of the PagedDataSource object.

Call the Getproductssortedaspageddatasource method and specify the value of the input parameter SortExpression

Once these are complete, the next step is to provide the parameter values. The ObjectDataSource of the Sortingwithdefaultpaging.aspx page is now configured to invoke the Getproductsaspageddatasource method and pass parameters through two querystringparameters, which The number is already specified in the SelectParameters set. These two querystringparameters parameters represent the pageindex and pageSize parameters of the Getproductsaspageddatasource method obtained from the QueryString.

Modify the ObjectDataSource SelectMethod property so that it calls the Getproductssortedaspageddatasource method. Then add a new QueryStringParameter to get the SortExpression parameter through the QueryString SortExpression field. Set the default value of QueryStringParameter to "ProductName".

Now the ObjectDataSource Declaration Markup language should look similar to the following:

<asp:objectdatasource id= "Productsdefaultpagingdatasource"
 oldvaluesparameterformatstring= "original_{0}" Typename= "PRODUCTSBLL"
 selectmethod= "Getproductssortedaspageddatasource"
 onselected= " productsdefaultpagingdatasource_selected "runat=" server >
 <SelectParameters>
 <asp: QueryStringParameter defaultvalue= "ProductName"
  name= "
  sortexpression" querystringfield= "SortExpression" Type= "String"/>
 <asp:querystringparameter defaultvalue= "0" name= "pageIndex" querystringfield= "
  PageIndex "type=" Int32 "/>
 <asp:querystringparameter defaultvalue=" 4 "name=" PageSize
  " Querystringfield= "PageSize" type= "Int32"/>
 </SelectParameters>
</asp:ObjectDataSource>

The Sortingwithdefaultpaging.aspx page is now sorted alphabetically by product name. See Figure 9. This is because the default value for the SortExpression parameter of the Getproductssortedaspageddatasource method is "ProductName".


Figure 9: Default sorted by ProductName

If you add a SortExpression querystring field manually-for example sortingwithdefaultpaging.aspx?sortexpression=categoryname– The result is sorted by the specified sortexpression. However, this sortexpression parameter is not included in the QueryString when you go to another page. In fact, we will return paging.aspx when the point or the next page. And there is currently no sort interface. The only way users can change the sort of data is by directly manipulating QueryString.

Create a Sort interface

We will first modify the Redirectuser method to redirect the user to the Sortingwithdefaultpaging.aspx page (instead of the paging.aspx) and include the SortExpression value in the QueryString. We should also add a read-only SortExpression property. This property is similar to the pageindex and PageSize properties created in the previous chapter and returns its value when the SortExpression QueryString field exists, otherwise the default value "ProductName" is used.

The Redirectuser method now receives only one parameter-the index of the displayed page. However, there may be times when we need to use sort expressions to redirect users to a page of specific data. We will immediately create a sort interface for this page that will contain button to sort the specified columns. When one of the button is clicked, we need to redirect the user by passing in the appropriate sort expression value. To provide this functionality, create two redirectuser methods. The first receives index of page and the second receives page index and sort expression (sort expression).

private string SortExpression
{
 get
 {
 if (!string). IsNullOrEmpty (request.querystring["SortExpression")) return
  request.querystring["SortExpression"];
 else return
  "ProductName";
 }
private void Redirectuser (int sendusertopageindex) {//Use the SortExpression property to get the
 sort Expressi
 on//
 from the QueryString Redirectuser (Sendusertopageindex, SortExpression);
}
private void Redirectuser (int sendusertopageindex, string sendusersortingby)
{
 //Send the user to the Requeste D page with the requested sort expression
 Response.Redirect (string. Format (
 "sortingwithdefaultpaging.aspx?pageindex={0}&pagesize={1}&sortexpression={2}",
 Sendusertopageindex, PageSize, Sendusersortingby));


In the first example of this chapter, we use DropDownList to create a sort interface. We will use 3 button (they are located above DataList) in this example-one for ProductName, one for CategoryName and one for SupplierName. Add three button and set their ID and text.

<p>
 <asp:button runat= "Server" id= "Sortbyproductname"
 text= "Sort by Product Name"/>
 : Button runat= "Server" id= "Sortbycategoryname"
 text= "Sort by Category"/> <asp:button runat=
 "Server" ID = "Sortbysuppliername"
 text= "Sort by Supplier"/>
</p>

Then create a click event handler for each button. This event handler invokes the Redirectuser method and returns the user to the first page with an appropriate sort expression.

protected void Sortbyproductname_click (object sender, EventArgs e)
{
 //Sort by ProductName
 Redirectuser (0, "ProductName");
}
protected void Sortbycategoryname_click (object sender, EventArgs e)
{
 //Sort by CategoryName
 Redirectuser (0, "CategoryName");
}
protected void Sortbysuppliername_click (object sender, EventArgs e)
{
 //Sort by SupplierName
 Redirectuser (0, "SupplierName");
}

The first time you browse the page, the data is sorted alphabetically by product name (see Figure 9). Click the Next button to browse the second page, and then click the Sort by Category button. This will let the page return to the first page and sort by category name, as shown in Figure 10. Similarly, the dot "Sort by Supplier" button sorts the data by Supplier and returns to the first page. The choice of sorting when data is paginated is recorded. Figure 11 is sorted by category and browses to page 13th.


figure 10:products Sorted by category


Figure 11: The sort Expression are noted when paging

Step Sixth: custom pagination for repeater

The DataList example in step fifth uses the default paging technology. When it comes to large amounts of data, we need to use custom paging. Back to efficiently paging through Large amounts of data and sorting custom Paged data, we learned the difference between the default and custom paging, and in the BLL for custom paging and custom paging The sort of data creates a method. In these two chapters we add the following three methods to the PRODUCTSBLL:

Getproductspaged (startRowIndex, Maximumrows) – returns a specific set of records that does not exceed the maximumrows starting from startRowIndex.
Getproductspagedandsorted (SortExpression, startRowIndex, Maximumrows) – returns a specific recordset based on the specified sortexpression.
Totalnumberofproducts () – Provides the total number of records for the Products table.

These methods can be used for efficient paging and sorting in DataList or Repeater. We first create a repeater that supports custom paging. And then add sort support. Open the Sortingwithcustompaging.aspx page under the Pagingsortingdatalistrepeater folder, add a repeater, and set the ID to products. Create a ObjectDataSource named Productsdatasource from the smart tag. Use the Getproductspaged method of the PRODUCTSBLL class to configure its select label.


Figure 12: Configuring ObjectDataSource

In the update, INSERT, delete tab, select (None) and click Next. Now we need to select the source for the startRowIndex and maximumrows parameters of the Getproductspaged method. In fact, there is no configuration required. The values of these two parameters are specified in the ObjectDataSource selecting event handler by the arguments attribute, as we specify SortExpression in the first example of this chapter. Therefore, select None in the Drop-down list for the parameter source.


Figure 13: Set the parameter source to None

  Note: Do not set the ObjectDataSource EnablePaging property to True. This allows ObjectDataSource to automatically include its startrowindex and maximumrows parameters in the list of existing parameters in SelectMethod. The EnablePaging property is useful when binding custom paging data to the GridView, DetailsView, and FormView. Since we are manually adding paging support for DataList and Repeater, we set them to False (the default), and we will implement these functions directly on the ASP.net page.

Finally, define the repeater ItemTemplate so that it displays only the name of the product ', category, supplier. After completing these, the Repeater and ObjectDataSource Declaration languages should look similar to the following:

<asp:repeater id= "Products" runat= "server" datasourceid= "Productsdatasource" enableviewstate= "False" > < itemtemplate>  

Now browse the page and note that no records are returned. This is because we have not yet specified the values of the startRowIndex and maximumrows parameters. To specify these values, create an event handler for the selecting event for ObjectDataSource and set the parameter values hard-coded to 0 and 5.

protected void productsdatasource_selecting
 (object sender, ObjectDataSourceSelectingEventArgs e)
{
 E. inputparameters["startRowIndex"] = 0;
 e.inputparameters["maximumrows"] = 5;
}

The first 5 product records are displayed when you browse the page.


Figure 14: Show Top 5 product

Note: The products listed in Figure 14 are sorted by product name because custom paging uses the getproductspaged stored procedure to return results that are sorted in ProductName.

In order for the user to be able to flip the page, we need to write down the Start row index and maximum rows during the postback process. In the default pagination example, we use QueryString to save these values. In this example we will use view state. Create the following two properties:

private int startRowIndex
{
 get
 {
 object o = viewstate["startRowIndex"];
 if (o = = null) return
  0;
 else return
  (int) o;
 }
 Set
 {
 viewstate["startrowindex"] = value;
 }
}
private int maximumrows
{
 get
 {
 object o = viewstate["maximumrows"];
 if (o = = null) return
  5;
 else return
  (int) o;
 }
 Set
 {
 viewstate["maximumrows"] = value;
 }
}

Then update the code for the selecting event handler, using the startRowIndex and Maximumrows properties instead of hard-coded 0 and 5.

e.inputparameters["startRowIndex"] = startRowIndex;
e.inputparameters["maximumrows"] = maximumrows;

Now our page still shows only 5 records. However, once these properties have been completed, we are ready to create the paging interface.

Add a paging interface

We still use the same as the default pagination example of the Previous, next, and last paging interface, and contains a label that shows which page and total number of pages are currently in the page. Add 4 button and 11 label below Repeater.

<p>
 <asp:button runat= "Server" id= "FirstPage" text= "<<" the "/>" <asp:button "runat=
 " Server "id=" PrevPage "text=" < Prev "/> <asp:button runat="
 server "id=" NextPage "text=" Next > "/>
 <asp:button runat= "Server" id= "LastPage" text= "last >>"/>
</p>
<p>
 < Asp:label runat= "Server" id= "Currentpagenumber" ></asp:Label>
</p>

Then create the Click event handlers for the 4 button. When one of the button is clicked, we need to modify the startRowIndex and rebind the data to repeater. The code for the first, Previous, and Next button is very simple, but for the last button, how do we determine the Start row index of the final page of data? To figure out the index– and determine if Next and last button should be enabled-we need to know the total number of paging data. We can call the Productsbll class's Totalnumberofproducts () method to get this total. Let's create a read-only property named Totalrowcount, which returns the result of the Totalnumberofproducts () method.

private int Totalrowcount
{
 get
 {
 //Return the value ' Totalnumberofproducts ()
 method PRODUCTSBLL Productsapi = new Productsbll ();
 return productsapi.totalnumberofproducts ();
 }

With this attribute, we can now get the Start row index of the last page. It can be obtained by Totalrowcount divided by the integer portion of the result of the maximumrows and then multiplied by maximumrows. We can now write click event handlers for the button in the 4 paging interface.

Finally, you need to disable the first and Previous buttons when browsing on page one, and disable Next and last buttons when browsing the final page. Add the following code to the selecting event handler in ObjectDataSource:

Disable The paging interface buttons, if needed firstpage.enabled = startRowIndex!=
0;
prevpage.enabled = startRowIndex!= 0;
int lastpagestartrowindex = ((TotalRowCount-1)/maximumrows) * maximumrows;
nextpage.enabled = startRowIndex < Lastpagestartrowindex;
lastpage.enabled = startRowIndex < Lastpagestartrowindex;

When you are done, browse to the page. See Figure 15. The first and Previous buttons are disabled when the page is browsed for the initial time. Point next displays the data for the second page. The last page of data is displayed (see Figures 16 and 17). Next and Last buttons are disabled when you browse the final page.


Figure 15: Previous and last Buttons are disabled when browsing the first page


Figure 16: second page data


Figure 17: Last page

I wish you a happy programming!

Introduction of the author

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.