It's fairly easy to get a paged ASP.NET ListView. All you have to do is to add an asp:DataPager into the list's template and you are done.
However, the page size is set statically inside the DataPager template:
This HOWTO explains how to controll the page size dynamically, for example using an external DropDownList with available page sizes. Functional requirements are as follows:
- the DropDownList should be initially bound to a value corresponding to the initial page size of the ListView (for example: we will have 5 available sizes on the list, 10, 20, 30, 50, 100 but the initial page size is 30. The DropDown should be then initially bound to the value 30)
- as the DropDownList's selection changes, the ListView should automatically set the new page size
First question: how are we supposed to get the actual page size of the ListView?
First answer: we have to search the List's template to get the DataPager and ask the pager for the list's size.
Second question: How do we set a new page size of the ListView?
Second answer: After we are able to find the current DataPager, we can use it's SetPageProperties method to set a new page size.
Third question: How do we set the initial value of the drop down list?
Third answer: We can bind the selection to the DataPager's PageSize property.
It seems then that the most important issue here to solve is to be able to retrieve the ListView's current DataPager. This is how it's done:
What is ControlHelper.Find( )? Well, it seems that the Control's FindControl method does not always work as expected. I got plenty of cases where FindControl does not find anything, while my custom Find finds what I expect to be found. Here it is:
After we've prepared the basics, the rest is rather simple. The DropDownList will have the AutoPostBack set to true. After the DropDownList postbacks to the server, we'll set a new page size of the ListView:
Additionally, as a nice bonus, we'll fill a description of the ListView saying how many total rows are there and which rows are currently visible:
Below is a screenshot from the example application.You can download the source code using the link provided at the top of the entry.