Friday 30 November 2007

SharePoint: Paging your results in SPGridView

To get SharePoint to handle paging in your webparts which are using GridView (SPGridView) you need to do a few tweaks to your code:

Just above your grid.DataBind() you need to insert the following code:

// Turn on paging and add event handler
grid.PageSize = 10;
grid.AllowPaging = true;
grid.PageIndexChanging +=
new GridViewPageEventHandler(grid_PageIndexChanging);

then add the event handler:
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}


If you are getting your the data set to bind to using a dynamic query, you might have a problem with the paging, since the state of the data set is not maintained. What was happening is that we we clicked on the next pages of the paging mechanism, the DataSet was lost, and thus all results in the GridView were lost. To maintain it, we stored the DataSet in the session, and this resolved our problem. I'm not sure whether is the right or the best solution, if anyone has better ideas please comment :)