Changing the Page Size Interactively in a DataGrid Web Control - The Problem (Page 2 of 5 )
The DataGrid server control enables easy paging through data. You can set the DataGrid to use paging and specify the page size, i.e. the number of records to display per page. However, letting the user to set interactively the page size one can easily run in trouble. Suppose the user is paging a DataGrid with a DataSource of 200 records and the PageSize property set to 5.
Suppose the user is looking at the last page (page number 40, CurrentPageIndex = 39) seeing the last five records: record number 196 to record number 200. Finally, suppose the user has the ability to change the PageSize to 10. Using only the build-in paging functionality, the DataGrid server control tries to re-display the current page, i.e. page number 40 or CurrentPageIndex = 39, but now there are only 20 pages with 10 records per page. So we end up with a nice error message: "Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount".
Let us find a solution that allows the user to set interactively the DataGird's PageSize property and meanwhile prevent the ugly break up of the application.
and I added the PageSizeChanged procedure to handle the SelectedIndexChanged event of the DropDownList control. This procedure sets the PageSize property of the DataGrid to the value of the text attribute of the selected item:
Sub PageSizeChanged(sender As Object, e As EventArgs) MyDataGrid.PageSize=CType(ddlPageSize.SelectedItem.Text, Integer) BindGrid End Sub
Note that I have enabled AutoPostBack for the DropDownList control.
You can try it out. So long you are displaying the first page you can change the page size as you like, the application works fine. If you try to change the page size while looking at another page, you might or you might not succeed. Whether it works or not depends on the page you are looking at and on the new page size you are setting up. After a few tries we come to a conclusion.
Changing interactively the page size is of no effect on the current value of the CurrentPageIndex property of the DataGrid control. This property remains unaltered. If the new re-arrangement of the data source according to the new value of the page size contains a page having the index equal to the value of CurrentPageIndex, we are lucky.
Otherwise the application ends with the known error message. Now it is clear that there must be a fine interplay between the PageSize and the CurrentPageIndex properties of the DataGrid control. Indeed, at the beginning there is such one, while the current page index takes values between 0 and PageCount-1 and PageCount depends on the total number of records and the page size.
Changing the PageSize we implicitly change the PageCount too, hence we change the admissible range for the current page index. If the CurrentPageIndex happens to be outside the new range, we are in trouble.