Paging ListView using DataPager without using DataSource Control

If you have already used the ASP.NET ListView and DataPager controls, you know how easily you can display your data using custom templates and provide pagination functionality. You can do that in only few minutes. The ListView and DataPager controls work perfectly fine in combination with DataSource controls (SqlDataSource, LinqDataSource, ObjectDataSource etc.), however if you use them with custom data collection, without using Data Source controls, you may find some unexpected behavior and have to add some little more code to make it work.

Note: I saw question related to this issue asked multiple times in different asp.net forums, so I thought it would be nice to document it here.

Lets create a working demo together…

1. Create sample ASP.NET Web Application project, add new ASPX page.

2. Add ListView control and modify the markup so that you will end up having this:

        <asp:ListView ID="ListView1" runat="server">
        <LayoutTemplate>
            <ul>
                <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
            </ul>
        </LayoutTemplate>
        <ItemTemplate>
            <li>
                <%# Eval("Name") %> (<%# Eval("Currency") %> <%# Eval("Price") %>)
            </li>
        </ItemTemplate>
        <EmptyDataTemplate>
            No data
        </EmptyDataTemplate>
        </asp:ListView>

The ListView control has three templates defined:

  • LayoutTemplate – where we define the way we want to represent our data. We have PlaceHolder where data from ItemTemplate will be placed. ListView recognizes this automatically.
  • ItemTemplate – where the ListView control will show the items from the data source. It makes automatically iterating over each item in the collection (same as any other data source control)
  • EmptyDataTemplate – If the collection has no data, this template will be displayed.

3. Add DataPager control and modify the markup in the following way:

        <asp:DataPager ID="lvDataPager1" runat="server" PagedControlID="ListView1" PageSize="5">
            <Fields>
                <asp:NumericPagerField ButtonType="Link" />
            </Fields>
        </asp:DataPager>


We add the DataPager control, associate it with the ListView1 control and add the PageSize property. After that, we need to define <Fields> where we put the field type and button type.

If we were binding from Data Source Control (SqlDataSource, LinqDataSource or any other…) this would be it and the ListView and DataPager would work perfectly fine. However, if we bind custom data collection to the ListView without using Data Source controls, we will have problems with the pagination.

Lets add custom data in our C# code and bind it to the ListView.

4. C# code adding custom data collection

- Define Product class

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Currency { get; set; }
}

- Define method that will create List of products (sample data)

List<Product> SampleData()
{
    List<Product> p = new List<Product>();
    p.Add(new Product() { Name = "Microsoft Windows 7", Price = 70, Currency = "USD" });
    p.Add(new Product() { Name = "HP ProBook", Price = 320, Currency = "USD" });
    p.Add(new Product() { Name = "Microsoft Office Home", Price = 60, Currency = "USD" });
    p.Add(new Product() { Name = "NOKIA N900", Price = 350, Currency = "USD" });
    p.Add(new Product() { Name = "BlackBerry Storm", Price = 100, Currency = "USD" });
    p.Add(new Product() { Name = "Apple iPhone", Price = 400, Currency = "USD" });
    p.Add(new Product() { Name = "HTC myTouch", Price = 200, Currency = "USD" });            
    return p;
}

This method should be part of the ASPX page class (e.g. inside _Default page class if your page is Default.aspx)

- Bind the sample data to ListView on Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindListView();
    }
}

void BindListView()
{
    ListView1.DataSource = SampleData();
    ListView1.DataBind();
}

Now, run the project and you should see the data displayed where only the first five items will be shown. The data pager should have two pages (1 2) and you will be able to click the second page to navigate to the last two items in the `collection.

Now, if you click on page 2, you will see it won’t display the last two items automatically, instead you will have to click again on page 2 to see the last two items. After, if you click on page 1, you will encounter another problem where the five items are displayed, but the data for the last two items in the ListView are shown (see print screen bellow)

 

If you notice in the previous two pictures, the behavior doesn’t seem to work properly. The problem here is that DataPager doesn’t know about current ListView page changing property. Therefore, we should explicitly set the DataPager Page Properties in the ListView’s PagePropertiesChanging event. Here is what we need to do:

1. Add OnPagePropertiesChanging event to ListView control

<asp:ListView ID="ListView1" runat="server" OnPagePropertiesChanging="ListView1_PagePropertiesChanging">

2. Implement the ListView1_PagePropertiesChanging method

protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
    //set current page startindex, max rows and rebind to false
    lvDataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

    //rebind List View
    BindListView();
}

Now, if you test the functionality, it should work properly.

Hope this was helpful.

Regards,
Hajan

Published Thursday, September 8, 2011 3:29 AM by hajan
Filed under: , , ,

Comments

# re: Paging ListView using DataPager without using DataSource Control

Wednesday, September 21, 2011 4:32 AM by Gjorgji Dimitrov

Nice approach, thanks for your contribution, i really appreciated. Best Regards, Gjorgji

# re: Paging ListView using DataPager without using DataSource Control

Tuesday, November 22, 2011 4:17 AM by lijo

good one

easy to under statnd

# re: Paging ListView using DataPager without using DataSource Control

Tuesday, December 6, 2011 11:49 PM by Soheil

finally a solution... I was looking for "ListView DataPager Custom DataSource" all over google for the past couple of days, your artivle didn't popup up. Now I searched for "DataPager Page 1" and voila!!

Thanks!

# re: Paging ListView using DataPager without using DataSource Control

Thursday, December 22, 2011 9:44 AM by Sumit

Thanks a Lot

:-)

# re: Paging ListView using DataPager without using DataSource Control

Saturday, January 7, 2012 6:00 AM by hajan

Thanks everyone for the comments! I am glad the article was helpful ;).

# re: Paging ListView using DataPager without using DataSource Control

Thursday, January 19, 2012 5:26 AM by John

Thanks! I was stuck on this for a while and this had me up and running in a few minutes.

# re: Paging ListView using DataPager without using DataSource Control

Monday, February 6, 2012 6:54 AM by neodescorpio

Thanks buddy , you rock :)

# re: Paging ListView using DataPager without using DataSource Control

Tuesday, February 21, 2012 12:02 PM by Thanh Tung

Very good.Thanks a lots.

# re: Paging ListView using DataPager without using DataSource Control

Friday, March 2, 2012 4:23 AM by Eva Janakieff

It's works fine!!!

Thanks!

# re: Paging ListView using DataPager without using DataSource Control

Friday, March 2, 2012 4:48 AM by Pawan Rahate

Thanks a lot. this helps me lot.

# re: Paging ListView using DataPager without using DataSource Control

Wednesday, March 21, 2012 5:45 AM by murali

Finally  i came here to get right solution...  Nice approach.. thanks a lot!:

# re: Paging ListView using DataPager without using DataSource Control

Friday, May 18, 2012 10:55 PM by Habib

Works like a charm. Thank you and well done.

# re: Paging ListView using DataPager without using DataSource Control

Tuesday, July 31, 2012 7:26 AM by Sajeda

Thanks this worked for me also

# re: Paging ListView using DataPager without using DataSource Control

Friday, October 26, 2012 3:15 PM by sina

thank you, that was so so so so so helpful!

# re: Paging ListView using DataPager without using DataSource Control

Monday, November 19, 2012 11:56 PM by Kasun

This is really helpful. Saved my day.

# re: Paging ListView using DataPager without using DataSource Control

Friday, December 14, 2012 1:56 AM by jaimin

'System.Web.UI.WebControls.ListView.SetPageProperties(int, int, bool)' is inaccessible due to its protection level

error fire

# re: Paging ListView using DataPager without using DataSource Control

Saturday, February 23, 2013 9:03 AM by Manish Y

Thanks very helpful

# re: Paging ListView using DataPager without using DataSource Control

Friday, March 8, 2013 10:35 AM by jfrank

cool!,

I was wondering how the example should be changed to make it more efficient, that is, if the collection has 5,000 items, if you load all the load could databinding listview or how to manipulate the pager to be would go all the appropriate consultations database

# re: Paging ListView using DataPager without using DataSource Control

Wednesday, August 28, 2013 8:59 AM by jay

superbbbbbbbbbbbbbb...i have been trying many complex codes from many articles since morning but this one made my pager working within minutes.

# re: Paging ListView using DataPager without using DataSource Control

Wednesday, November 27, 2013 3:46 PM by Piotr Wolski

Nice one - much simpler than the Take().Skip() approach I use to use at the point when getting the data back! Thanks!

Leave a Comment

(required) 
(required) 
(optional)
(required)