# GridView and Invalid CurrentPageIndex Value Exception

There are many developers who have faced the page index problems using GridView. Specially, if GridView supports deleting. Also one may face page index going out of range when there are multiple users managing same data. Here is my little advice about how to avoid page index problems when using GridView.

### How to produce "Invalid PageIndex value" exception

Let’s produce this exception intentionally. We have to bind GridView to some data source and enable paging. Before we bind GridView to data we have to set current page index. If we have 10 pages of data then let’s say that current page index is 15.

protected void Page_Load(object sender, EventArgs e){    if (this.IsPostBack)        return;     gdvList.PageIndex = 15;    gdvList.DataSource = GetRows();    gdvList.DataBind();}

As a result we will get the following error.

Now, let’s see what we can do to avoid this error.

### Fixing page index

If there is custom control class that extends GridView it is more convenient to add the following code to this class so this feature is available in all GridViews used in project. If there is no custom class then we have to write some additional code before binding GridView to data.

To corrigate the page index our method has to know to things:

1. count of elements in data source,
2. GridView object that has index we want to corrigate.

This method can be added to some utility class in project.

public static void CorrectCurrentPage(Int32 count, GridView gdv){    Int32 newIndex = gdv.PageIndex;     if (gdv.PageSize > 0)        if ((Int32)Math.Ceiling(count / gdv.PageSize) < newIndex)            newIndex = (Int32)Math.Ceiling(count / gdv.PageSize);    if (newIndex < 0)        newIndex = 0;    gdv.PageIndex = newIndex;}

This method is pretty universal and if it is needed it is not hard to rewrite it for DataGrid by example. Now, why we give elements count to this method but not the object with data? The reason is simple – we don’t want to know what is the data source of GridView. Is it somethings based on IEnumerable interface or is it DataTable or is it something else. All we need to know is elements count so we don’t have to handle different data sources in this method.

Let’s extend the first code example with one line and let’s see what happens.

protected void Page_Load(object sender, EventArgs e){    if (this.IsPostBack)        return;    DataTable dt = GetRows();    gdvList.PageIndex = 15;    gdvList.DataSource = dt;    CorrectCurrentPage(dt.Rows.Count, gdvList);    gdvList.DataBind();}

Now, if current page index is bigger than pages count in GridView then we have last page in GridView as current page. If current page has too low value then we have 0 as current page index. This way you can be sure that there is no problems related to running out of page indexes.