KnowDotNet Visual Organizer

Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount
How to Prevent This Error

by Les Smith
Print this Article Discuss in Forums

I am getting an error in my DataGrid saying, "Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount".  What is the problem.<BR>
The problem is as stated; you have an invalid CurrentPageIndex.  This can happen for several reasons, when the DataGrid is set to AllowPaging.  Several solutions have been proposed on the Web that I have found, but I did not see one that would work in all cases, especially when you are re-binding the DataGrid and the CurrentPageIndex is set higher than the number of pages of data when the grid re-binds.

The code shown below will work properly, even when there is no data in the filtered DataView.  Some others have posted solutions such as decrementing the CurrentPageIndex if you receive the subject error.  However, the problem with that is that you don't know whether that will correct the problem, without calculating a valid CurrentPageIndex based on the number of rows that you are going to display, assuming there are any rows at all.  The real solution is to attempt to place the user on the first page, because they probably have modified or filtered the data, and that is why the grid is being rebound.  In that case, it is not significant what page they are on.  Obviously, a little more elegant solution is required if there is data in the grid and the user just deleted one row, etc.  That will require calculations and still you may need multiple try/catches.


      this.DataGrid1.DataSource=dv;

      // the currentpageindex must be >= 0 and < pagecount<BR>       try
      {
        this.DataGrid1.DataBind();
        this.DataGrid1.Visible=true;

      }
      catch
      {
        try
        {
          this.DataGrid1.CurrentPageIndex=0;
          this.DataGrid1.DataBind();
          this.DataGrid1.Visible=true;

        }
        catch
        {
          this.lblError.Text="No data for selection";
          this.lblError.Visible=true;
        }
      }

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing