Bucket
Bucket

Reputation: 641

.NET Gridview SetPageIndex not working as expected

The MS documentation and tool tip for SetPageIndex says

Sets the page index of the System.Web.UI.WebControls.GridView control by using the row index

I had a GridView with 40 rows and 10 rows per page. Passing row index 0 rendered the first page as expected. Passing row index of 39 rendered the last page again as expected.

Passing the row index of 14 should render the second page, it did not it displayed the last page. Passing row index of 1 should select the first page, it display the second page.

Upvotes: 2

Views: 633

Answers (1)

Bucket
Bucket

Reputation: 641

Turns out the MS documentation does not match the behavior. When the GridView paging footer fires the PageIndexChanging event the NewPageIndex property of the GridViewPageEventArgs is in the range less than GridView.PageCount

When PageIndexChanging is fired by calling SetPageIndex the value of NewPageIndex is the same as the row index passed in. The value has not been altered as the documentation would suggest.

The solution is to calculate the page index from the from row index your self before calling SetPageIndex.

if (rowIndex <= 0)
pageIndex = 0;
else
 {
   pageIndex = (int)Math.Floor((double)rowIndex / (double)myGridView.PageSize);
 }
myGridView.SetPageIndex(pageIndex);

Upvotes: 2

Related Questions