Simple Paging in Repeater and DataList Controls

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
Simple Pag ing in Repeater and DataList Controls  
      
   

[Rate this Article]

introduction
Most of the times while creat ing database driven web pages like product list ing, employee directory, etc. we display the data in grid format. ASP.NET has come up with Web Controls like DataGrid, DataList and Repeater that allow you to display your data in tabular format easily.

Amongst the above three Web Controls the DataGrid Control is the most advanced and supports Pag ing, templates etc. The other two Controls are used in places where you need more control over the render ing of your data. The DataList and Repeater Controls have very flexible templates that give you total control over the formatt ing of your data, but one of the major drawbacks of these Controls is that they do not support Pag ing!!

Pag ing simply means splitt ing 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, you have a web page display ing your products list ing. It would not be a good idea to show all the 1000+ products you are offer ing on the one s ingle page, s ince it will make the page difficult to browse as well as it will 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 not a good idea is that the client would not want to know about all the products you are sell ing s ince the last 10 years, he might visit to page to look out for the new products that you are offer ing.
in such scenarios, you divide the display of data into different pages and then display say 10 - 20 items per page and provide the client with l inks to view additional pages, this is called Pag ing.
Remember we are us ing server-side script ing so you don't have to physically create all the pages, you just have to code one page in such a way that it keeps Pag ing all the records.

Hence some of the merits of Pag ing are:
1) Easy to browse pages.
2) Faster to load pages on client side s ince the amount to display per page is less.
3) Less load on the database server, s ince for every user you only pull out a limited amount of data, rather than pull ing out all 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 you might want to use these Controls. Even though these Controls do not support Pag ing internally, in this article I will display a method us ing which, you can easily enable Simple Pag ing (previous , next ) in your DataList and Repeater Controls.

25 October 2002, Update: The small error in the BuildPagers method has been corrected. Thanks to all readers who po inted out the bug!

Requirements
1) ASP.NET v1
2) SQL Server 7.0/2000/MSDE
(Optional, I am go ing to use the Northw ind database that installs with the .NET SDK)

Simple Pag ing in Repeater Control

1) List ing 1, shows the code for a normal page that selects all records from the Products table and displays it us ing the Repeater control.

<%@ Page Language="C#" debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
  void Page_Load( Object sender , EventArgs e)
  {
    //Build the Grid only if the page has been accessed for the first time
    if( !IsPostBack )
      BuildGrid();
  }

  public void BuildGrid()
  {
    SqlConnection myConnection =
          new SqlConnection(
      "server=(local)//NetSDK;database=Northw ind;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");
    //DataB ind the Repeater
    My Repeater.DataSource = ds.Tables["Products"].DefaultView;
    My Repeater.DataB ind();
  }
</script>
<body>
<h1>Products List ing</h1>
<form runat="server">
  <ASP: Repeater id="My Repeater" runat="server">
      <HeaderTemplate>
        <table width="100%" border="1" cellpadd ing="1" cellspac ing="2">
          <tr>
            <th>
              Product ID
            </th>
            <th>
              Product
            </th>
            <th>
              Quantity Per Unit
            </th>
            <th>
              Unit Price
            </th>
          </tr>

      </HeaderTemplate>

      <ItemTemplate>
        <tr>
          <td>
            <%# DataB inder.Eval(Conta iner.DataItem, "ProductID") %>
          </td>
          <td>
            <%# DataB inder.Eval(Conta iner.DataItem, "ProductName") %>
          </td>
          <td>
            <%# DataB inder.Eval(Conta iner.DataItem, "QuantityPerUnit") %>
          </td>
          <td>
            <%# DataB inder.Eval(Conta iner.DataItem, "UnitPrice", "$ {0}") %>
          </td>
        </tr>
      </ItemTemplate>

      <FooterTemplate>
        </table>
      </FooterTemplate>

  </ASP: Repeater>

</form>
</body>
</html>

List ing 1 - Simple Repeater Control
2) The first step to enable Pag ing in this page is to add three hidden Html Controls that will ma inta in the values necessary for Pag ing. You can add these Controls below after your Repeater control.

< input type="hidden" id="PageSize" value="10" runat="server">
< input type="hidden" id="CurrentPage" value="1" runat="server">
< input type="hidden" id="TotalSize" runat="server">
List ing 2 - Hidden Html Controls

The first control with the id PageSize is used to def ine the number of records you want to display per page. Current I have set it to display 10 records, you can set it to a value you wish.
The second control with the id CurrentPage is used to track the current page that's been displayed. Usually you want to start display ing the records from the first page so we set the value of this control to 1.
Lastly, the control with the id TotalSize is used to store the count of the total number of records available.

3) Next, we add two L inkButton Controls that will enable navigation to the previous and next pages. Add these Controls below the Repeater control def inition.
Note: You might be tempted to include these Controls with in your Repeater control's FooterTemplate, but I advise you not to follow this approach s ince it will complicate matters much more while writ ing code to h andle these buttons it will be very difficult to get a reference to these Controls.

<asp:L inkButton id="Prev" Text="<< Previous" OnClick="Page_ Repeater" runat="server" />  
<asp:L inkButton id="Next" Text="Next >>" OnClick="Page_ Repeater" runat="server" />
List ing 3 - L ink Buttons

List ing 3, def ines the two L inkButtons with the id Prev and Next respectively. Feel free to change the Text property of these Controls to someth ing appropriate to your implementation. Also note that I have set the OnClick event of both these Controls to one s ingle event h andl ing method called Page_ Repeater. List ing 4 displays the Page_ Repeater method code.

public void Page_ Repeater( object sender, EventArgs e )
{
  //Check for Button clicked
  if( ((L inkButton)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 ).ToStr ing() ;
    }
  }
  else if( ((L inkButton)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 ).ToStr ing() ;
    }
  }
  //Rebuild the Grid
  BuildGrid();
}

List ing 4: Page_ Repeater method

in the Page_ Repeater method I first check which of the button was clicked.
If the Prev L inkButton was clicked, I check the value of the control with id CurrentPage. If the current value m inus 1 is 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 L inkButton was clicked, I check out if the product of the Controls with id's CurrentPage and the PageSize is less than the value of the control with id TotalSize, indicat ing that I have more pages to display. Hence I increment the value of the control with id CurrentPage.
Lastly, the BuildGrid method is given a call to re-build the Repeater.

4) The current BuildGrid method is configured to fetch all the records from the database. As I had stated earlier this is a bad practice and only limited records should be fetched each time to increase scalability of your web site. in List ing 5, below I modify the BuildGrid method so that it only pulls out the required records from the database.
in case you are data b ind ing your control to a DataReader rather then a DataSet, then you will have to modify your SQL Statement appropriately so that only the required records are fetched.

  public void BuildGrid()
{
  SqlConnection myConnection =
    new SqlConnection(
      "server=(local)//NetSDK;database=Northw ind;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 first 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");

  //DataB ind the Repeater  
  My Repeater.DataSource = ds.Tables["Products"].DefaultView;
  My Repeater.DataB ind();

  //Second Part
  //Create a new Comm and to select the total number of records
  SqlComm and myCmd = new SqlComm and( "SELECT Count(*) FROM Products", myConnection );
  myConnection.Open();
  //retrieve the value
  TotalSize.Value = myCmd.ExecuteScalar().ToStr ing() ;
  myConnection.Close();
}

List ing 5 - Modified BuildGrid method

As its clear from List ing 5, the only change I have made is that now I use a different overload of the Fill method that takes the start index and the number of records to fetch along with the st andard DataSet and table name. Us ing this overload reduces the amount of data fetched from the database increas ing the performance of your application.
Next, I construct and execute another query that returns the total number of records the database conta ins. This value is then stored to the control with id TotalSize. Remember that we cannot get the total records count from the DataSet s ince our updated Fill method only returns the necessary number of records. in your own implementation you will have to change this SQL query appropriately to return the number of records present in the database.
You can leave this second part out from your code if you 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 change frequently you can encapsulate the second part in an if( !IsPostBack ) structure, so that the total number of records is only retrieved the first time the Repeater is built.
<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值