Tuesday, March 14, 2006

Why is DataGrid.PageCount = 1?

Came across an issue today that was not obvious how to fix, and Googleing revealed no information about it, maybe I just couldn't hit upon the right combination of search terms, but here you go. In ASP.NET, a page that I am working on displays data with a DataGrid. I don't like, nor do any of our users, the built-in paging controls that you get for free with the DataGrid, so we wanted to implement something custom. I found this article on DotNetJunkies.com demonstrating how they did it. They go whole hog and used a stored procedure to implement entirely custom data page management. I have done this before too, but I have a lot of code using DataViews and DataSets already in this page (inherited from someone else) that I don't want to refactor during this phase of development. So I turn off the built-in paging controls with this bit of markup <asp:datagrid id="DataGrid1" AllowPaging="True" PagerStyle-Visible="False"
AllowCustomPaging="True">...</asp:datagrid>
There is just one problem with this, when you have AllowCustomPaging="True", then no matter what you set as DataGrid1.DataSource and do the DataGrid1.DataBind, your DataGrid1.PageCount property will always be 1. I think I copied this out of the DotNetJunkies article because I thought I might replace the way I get data into the DataGrid as well as the paging UI, and forgot about. In MSDN help, the fact that this will always be 1 when AllowCustomPaging is true is not mentioned. In the help for AllowCustomPaging, the only hint there may be a relationship to PageCount is the note that you have to set the VirtualItemCount to the total number of items there could be. When you do, then PageCount is calculated correctly based on the PageSize. The relationship between all these properties is not obvious and if you haven't dealt with this issue in a while, it may take a while to determine why PageCount=1 like it took me. I hope this post saves someone some time.