Simple paging in Repeater and DataList Controls

Source: Internet
Author: User
Tags count eval prev table name tostring
Simple paging in Repeater and DataList Controls



[Rate this Article]

Introduction
Most of the Times while creating database driven Web pages like product listing, employee directory, etc. we display the D ATA in grid format. ASP.net has come up with Web Controls like DataGrid, DataList and Repeater this allow to display your data in tabular Format easily.

Amongst the above three Web Controls the DataGrid control is the most advanced and supports paging, templates etc. The other two controls are used at places where you are need more control over the rendering of your data. The DataList and Repeater Controls have very flexible templates that give your total control over the formatting of your DA TA, but one of the major drawbacks of these controls are that they does not support

Paging simply means splitting data display (UI) over number of pages in order to facilitate easy to browse interface and M Inimize the data sent out to the client.
For example, your have a Web page displaying your products listing. It would not being a good idea to show all of the 1000+ products for your are offering on the one single page, since it'll make the Page difficult to browse as as as the it'll take a lot of time to display on the clients browser due to the size of data (plus a heavy load on your server).
The second reason this is isn't a good idea are that the client would isn't want to know about all of the products for you are selling Since the last ten years, he might visit to page to look out for the new products this you are offering.
In such scenarios, your divide the display of data into different pages and then display say 10-20 items per page and Pro Vide the client with links to view additional pages, which is called paging.
Remember we are using server-side scripting so don ' t have to physically create all of the pages, you just have to code on E page in such a way which it keeps paging all the records.

Hence some of the merits of paging are:
1 easy to browse pages.
2) faster to load pages on client side since the amount to display each page is less.
3) Less load on the database server, since for every user to pull out a limited amount of data, rather than Out all of the records for each client.

As I mentioned before, the DataList and Repeater controls are very flexible and there would be a large number of places yo U might want to use these controls. Even though these controls does not support paging internally, in this article I'll display a method using which, can Easily enable simple paging (previous, next) in your DataList and Repeater controls.

October 2002, Update:the small error in the Buildpagers method has been. To all readers who pointed out the bug!

Requirements
1) ASP.net v1
2) SQL Server 7.0/2000/MSDE
(Optional, I am going to use the Northwind database this installs with the. NET SDK)

Simple paging in Repeater control

1) Listing 1, shows the code for a normal page which selects all records to the Products table and displays it using the Repeater control.

<%@ Page language= "C #" debug= "true"%>
<%@ Import namespace= "System.Data"%>
<%@ Import namespace= "System.Data.SqlClient"%>
<script language= "C #" runat= "Server" >
void Page_Load (Object sender, EventArgs e)
{
Build the Grid only if the page has been accessed for the
if (! IsPostBack)
Buildgrid ();
}

public void Buildgrid ()
{
SqlConnection myconnection =
New SqlConnection (
"Server= (local) \\netsdk;database=northwind; Trusted_connection=yes ");
SqlDataAdapter myadapter =
New SqlDataAdapter (
"Select ProductID, ProductName, QuantityPerUnit, UnitPrice from Products",
MyConnection);
Fill the DataSet
DataSet ds = new DataSet ();
Myadapter.fill (ds, "products");
DataBind the Repeater
MyRepeater.DataSource = ds. Tables["Products"]. DefaultView;
Myrepeater.databind ();
}
</script>
<body>
<form runat= "Server" >
<asp:repeater id= "MyRepeater" runat= "Server" >
<HeaderTemplate>
<table width= "100%" border= "1" cellpadding= "1" cellspacing= "2" >
<tr>
<th>
Product ID
</th>
<th>
Product
</th>
<th>
Quantity per unit
</th>
<th>
Unit Price
</th>
</tr>

</HeaderTemplate>

<ItemTemplate>
<tr>
<td>
<%# DataBinder.Eval (Container.DataItem, "ProductID")%>
</td>
<td>
<%# DataBinder.Eval (Container.DataItem, "ProductName")%>
</td>
<td>
<%# DataBinder.Eval (Container.DataItem, "QuantityPerUnit")%>
</td>
<td>
<%# DataBinder.Eval (Container.DataItem, "UnitPrice", "$ {0}")%>
</td>
</tr>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>

</ASP:Repeater>

</form>
</body>

Listing 1-simple Repeater Control
2 The ' the ' the ' the ' the ' the ' the ' the ' the ' the ' the ' the ' three ' to-enable paging in the page Ry for paging. You can add this controls below after the Your repeater control.

<input type= "hidden" id= "PageSize" value= "a" runat= "Server" >
<input type= "hidden" id= "CurrentPage" value= "1" runat= "Server" >
<input type= "hidden" id= "totalsize" runat= "Server" >
Listing 2-hidden Html Controls

The ' the ' used to define the number of the ' the ' is ' the ' PageSize is ' records you want to display per page. Current I have set it to display records, can be set it to a value of you wish.
The second control with the ID currentpage are used to track the "current page" been displayed. Usually you want to start displaying the records from the ' The ' the ' the ' the ' the ' the ' the ' of this ' is ' the ' the ' of '
Lastly, the control with the ID totalsize are used to store the count of the total number of records available.

3 Next, we add two LinkButton controls that'll enable navigation to the previous and next pages. Add These controls below the Repeater control definition.
Note:you might is tempted to include this controls within your Repeater control ' s FooterTemplate, but I advise o follow this approach since it would complicate matters much of while writing code to handle these buttons it would be ve Ry difficult to get a reference to these controls.

<asp:linkbutton id= "Prev" text= "<< Previous" onclick= "Page_repeater" runat= "Server"/>
<asp:linkbutton id= "Next" text= "Next >>" onclick= "Page_repeater" runat= "Server"/>
Listing 3-link Buttons

Listing 3, defines the two linkbuttons with the ID Prev and Next respectively. Feel free to change the Text of the "controls to something appropriate to your implementation. Also Note This I have set the OnClick event of both these controls to one single event handling method called R. Listing 4 Displays the Page_repeater method code.

public void Page_repeater (object sender, EventArgs e)
{
Check for Button clicked
if (((LinkButton) sender). ID = = "Prev")
{
Check If we are on any page greater than 0
if (int. Parse (Currentpage.value)-1) >=0)
{
Decrease the CurrentPage Value
Currentpage.value = (int. Parse (Currentpage.value)-1). ToString ();
}
}
else if ((LinkButton) sender). ID = = "Next"
{
Check If we can display the next page.
if (int. Parse (currentpage.value) * Int. Parse (Pagesize.value))
< int. Parse (Totalsize.value))
{
Increment the CurrentPage value
Currentpage.value = (int. Parse (Currentpage.value) + 1). ToString ();
}
}
Rebuild the Grid
Buildgrid ();
}

Listing 4:page_repeater method

In the Page_repeater method I-Check which of the button was clicked.
If the Prev LinkButton is clicked, I Check the value of the control with ID currentpage. If the current value minus 1 are greater than equal to 0, it indicates I have previous pages to display. So I decrement the value of the control with ID currentpage by 1.
If the Next LinkButton was clicked, I check out if the product of the controls with ID ' s currentpage and the PageSize is L ESS than the value of the control with ID TotalSize, indicating I have more pages to display. Hence I Increment the value of the control with ID currentpage.
Lastly, the Buildgrid method was given a call to re-build the Repeater.

4) The current Buildgrid method are configured to fetch all the records from the database. As I had stated earlier this are a bad practice and only limited records the should be fetched each time to increase scalabilit Y of your Web site. In Listing 5, below I Modify the Buildgrid and so this it only pulls out of the required records from the database.
In the case you are the data binding your control to a DataReader rather then a DataSet, then your would have to modify your SQL Sta Tement appropriately so this only the required records are fetched.

public void Buildgrid ()
{
SqlConnection myconnection =
New SqlConnection (
"Server= (local) \\netsdk;database=northwind; Trusted_connection=yes ");
SqlDataAdapter myadapter =
New SqlDataAdapter (
"Select ProductID, ProductName, QuantityPerUnit, UnitPrice from Products",
MyConnection);
Fill the DataSet
DataSet ds = new DataSet ();

Get the start record Count
Remember database count is zero based so decrease the value of
The current page
int startrecord = (int. Parse (Currentpage.value)-1) *
Int. Parse (Pagesize.value);
Fetch only the necessary records.
Myadapter.fill (ds, Startrecord, int.) Parse (Pagesize.value), "products");

DataBind the Repeater
MyRepeater.DataSource = ds. Tables["Products"]. DefaultView;
Myrepeater.databind ();

Second part
Create a new Command to select the total number of records
SqlCommand mycmd = new SqlCommand ("SELECT Count (*) from the products", myconnection);
Myconnection.open ();
Retrieve the value
Totalsize.value = Mycmd.executescalar (). ToString ();
Myconnection.close ();
}

Listing 5-modified Buildgrid method

As its clear from Listing 5, the ' only change I have made ' is ' that ' I use a different overload of the ' Fill method ' that Ta Kes the start index and the number of records to fetch along with the standard DataSet and table name. Using This overload reduces the amount of data fetched from the database increasing the performance of your application.
Next, I construct and execute another query that returns the total number of records the database contains. This value is then stored to the control with ID totalsize. Remember that we cannot get the total records count to the DataSet since our updated Fill method only returns the Necess ary number of records. In your own implementation you'll have to change this SQL query appropriately to return the number of records present in The database.
Can leave this second part out of your code if your just want to display a fixed number of pages and directly set the Value of the control with ID totalsize manually. If the number of records does not is frequently you can encapsulate the second part into an if (! ISPOSTBACK) structure, so this total number of records are only retrieved the "a", the Repeater is built.



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.