German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Custom Paging for a Datalist or Repeater Control

Written by omerkamal on Jul 04, 2007
Develop a customised paging ability for your Datalist or Repeater Control using ASP .NET 2.0

What is Paging?                                                                                Download: DatalistPaging.zip

If there is a lot of data which cannot be presented in a one page then we divide the data in different Pages. This method is called Paging.

In a Gridview paging is already built-in. Gridview is useful for multi-Column data. If there is only one Column to display and it have to repeat the same Style then we use either DataList or Repeater Control. But, with these controls problem is that we don’t have built-in paging property. So here we are going to take this case. We will explain that how Custom Paging can develop.

 

Explanation:

We  are going to create a datalist populated with data of registered users to a website. We will also use the Users Uploaded images to their Profile and their current status.

 

<asp:DataListID="UserDataList" runat="server" RepeatDirection="Horizontal" RepeatColumns="4" DataSourceID="ObjectDataSource1">

<ItemTemplate>

   <table align="center">

<tr>

    <td>       

<a href='UserProfile.aspx?userN=<%# Eval("Name") %>'>

<img alt='<%# Eval("Name") %> Profile Image'

src='PicHandler.ashx?Size=M&UserName=<%# Eval("Name") %>'/>

a>

   td>

tr>

<tr>

          <td>

  <%# Eval("Name") %>

  <br />

  <%# Eval("Online") %>

          td>

tr>

   table>

ItemTemplate>

asp:DataList>

 

What we are doing?

1.       RepeatColumns="4" means that DataList will have 4 Columns.

2.       RepeatDirection="Horizontal" Datalist will repeat itself in horizontally.

3.       We are using Custom Template ItemTemplate of DataList to create our desired Layout.

4.       User Image is beeing accessed through the ASP .NET Handler “PicHandler.ashx”. For more information how to work with Database images please read  Save and Display Images using ASP .NET 2.0 Profile

5.         <%# Eval("Name") %> Is a data binding method to access a returned data filed. Here, we are accessing the Name field from the ObjectDataSource1

 

Now, we will creat or Navigation code or say Paging Template. This can be Inject under or above the DataList. We will controle the View by our Code behind, which we are going to explain later. This will show the Next, Previous and Current Pager Location.

 

<div id="Navigation" class="navigation" runat="server">

<div id="leftnav">

  <a id="PreviousPageNav" runat="server"><< Previousa>

div>

<div id="rightnav">

   <a id="NextPageNav" runat="server">Next >>a>

div>

<div id="numnav">

 <asp:Label ID="PagerLocation" Text="a Number" runat="server" />

div>

div>

 

So how are we accessing the Data? And, from Where comes the Data? We are going to create our own methods to create the Users Data which will be extracted from built-in Membership database of ASP .NET 2.0. For that we   ObjectDataSource. GetUsersData Is a Class name in App_Code folder GetAllUsersDataTableByPageIndex  and is our Select Method. We need a Parameter to pass to the method for the current Page i.e SelectParameters, this job will be performed through QueryStringParameter, here perticularly PageIndex. That means: for every page view we will pass a QueryString to the method and it will return the page Data.

 

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="GetUsersData" SelectMethod="GetAllUsersDataTableByPageIndex" OnSelected="DataSource_Selected" OldValuesParameterFormatString="original_{0}">

<SelectParameters>

<asp:QueryStringParameter DefaultValue="0" Name="PageIndex" QueryStringField="PageIndex" Type="Int32" />

SelectParameters>

asp:ObjectDataSource>

Let’s have a look on the method which is the Heart of all  Process. One more time this the function which is created in GetUsersData Class (create the class inside App_Code folder):

public static DataTable GetAllUsersDataTableByPageIndex(int pageIndex)

{

        MembershipUserCollection mc = Membership.GetAllUsers();

 

        DataTable dt = new DataTable("Users");

        dt.Columns.Add("Name", typeof(string));

        dt.Columns.Add("Online", typeof(string));

       

        // initialize to next value

        int UpperIndexNextPage = (pageIndex + 1) * 12;

       

        int LowerIndexNextPage = UpperIndexNextPage - 11;

 

        // If upper limit is less then supposed one then reduce

        // to the actual Lower value will stay the same

        if (UpperIndexNextPage > mc.Count)

        {

            UpperIndexNextPage = mc.Count;

        }

        // Make sure that Next page Lower value is under the Upper Limit.

        // If its only 1 then make the both upper and lower limits same

        if (LowerIndexNextPage == mc.Count)      

        {

            LowerIndexNextPage = 1;

            UpperIndexNextPage = 1;

        }

 

        // Create Users Array.

        string[] users = new string[mc.Count];

        int i = 0;

        foreach (MembershipUser st1 in mc)

        {

            users[i] = st1.UserName;

            i += 1;

        }

       

        // Fill the DataTable, Notice how to see the user Current Status.

        string name = string.Empty;

        string status = string.Empty;

        for (int j = LowerIndexNextPage - 1; j < UpperIndexNextPage; j++)

        {

            MembershipUser user = Membership.GetUser(users[j], false);

            name = users[j];

            if (user.IsOnline)

                status = @" Online ";

            else

                status = "Offline";

 

            dt.Rows.Add(new Object[] { name, status });

        }

 

        dt.AcceptChanges();

        return dt;

    }

 

We created a DataTable and filled it with Users data. But we are caring the upper limit and lower limit for the data rows to be return. This is decided through the PageIndex value passed from the Page Query String value. For further reading how to create Data Table please read:

1.       Creating a DataTable Dynamically from MS SQL Data Source

2.       Create a DataTable of All User in your Website

 

Now, we are going to develop the Code behind for the Page.  At every page Refresh the DataSource_Selected is executed. Here is where we manage the Page Size and the Paging Template:

protected void DataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)

    {

        // Retrieve output parameter values returned from calling the

        // "ProductsTableAdapter.GetProductsByCategoryId"

        // method invoked by the ObjectDataSource control

        MembershipUserCollection mc = Membership.GetAllUsers();

        int UsersCount = mc.Count;

 

        // from ObjectDataSource parameter pageIndex

        int pageIndex = Convert.ToInt32(Request.QueryString["PageIndex"]);      

        int pageSize = 12;

 

        UpdatePagerLocation(pageIndex, pageSize, UsersCount);

        UpdateNextPrevLinks(pageIndex, pageSize, UsersCount);

 

        Page.Title = "FriendsPoint.de | Members List: ";

    }

 

    void UpdatePagerLocation(int pageIndex, int pageSize, int UsersCount)

    {

 

        int currentStartRow = (pageIndex * pageSize) + 1;

        int currentEndRow = (pageIndex * pageSize) + pageSize;

 

        if (currentEndRow > UsersCount)

            currentEndRow = UsersCount;

 

        PagerLocation.Text =

 currentStartRow + "-" + currentEndRow + " of " + UsersCount + " Users";

    }

 

    void UpdateNextPrevLinks(int pageIndex, int pageSize, int UsersCount)

    {

 

        string navigationFormat = "UsersWidPics.aspx?PageIndex={0}";

 

        PreviousPageNav.HRef =

        String.Format(navigationFormat, pageIndex - 1);

        PreviousPageNav.Visible = (pageIndex > 0) ? true : false;

 

        NextPageNav.HRef = String.Format(navigationFormat, pageIndex + 1);

        NextPageNav.Visible =

                   (pageIndex + 1) * pageSize < UsersCount ? true : false;

    }

Download the code for more detail.               Download: DatalistPaging.zip

Visitors/Readers Comments
(for questions please use The Forum)



Haissam Abdul Malak

Actually i have written an article on creating custom paging for datalist control on www.dotnetslackers.com

P.S: For future publishing try to insert some images to better demonstrate your idea.

Anyhow good article.

HC

04/07/2007 16:58:34 UTC

Sameena

Thanks a lot!

Very well explained.

11/09/2007 05:41:58 UTC

sandeep kumar
this is sandeep from vidushiinfotech hi i love this site very much its really very usefull for the dotnet lovers

14/09/2007 07:32:19 UTC

rajesh

Hi thanks

its very help to me

28/09/2007 07:46:07 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)