Part 2: Extending your SPGridview with paging controls
In Part 1: Using SPGridview, adding menus, grouping and sorting I looked at how to use an SPGridView from the ground up to bind to a custom DataSet. One of the features I omitted at the time was paging:
Jason Wang already has a good post on the subject, but I’m going to continue my example with some pretty verbose code so hopefully things will just work first time for you. There is a gotcha – in order to display the paging tabs PagerTemplate needs to be set to null after the grid is added to the controls collection but before BindData is called; and you’ll need to give some extra consideration if you’re also using sorting.
In Part 3 by the way, I really want to cover filtering, but it’s proving tricky stuff, due to the way SPGridView is designed to process the filtering callback. At least I understand the problem - more on that shortly.
Extending your code
Pop this code just above oGrid.DataBind():
// Turn on paging and add event handler
oGrid.PageSize = 3;
oGrid.AllowPaging = true;
oGrid.PagerTemplate = null; // Must be called after Controls.Add(oGrid)
// Recreate current sort if needed
if (ViewState["SortDirection"] != null && ViewState["SortExpression"] != null)
// We have an active sorting, so this need to be preserved
oView.Sort = ViewState["SortExpression"].ToString()
+ " " + ViewState["SortDirection"].ToString();
and add the event handler:
void oGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
oGrid.PageIndex = e.NewPageIndex;
The extra lines around sorting are important if you enabled sorting on the list in Part 1. Adding the paging means CreateChildControls() could now fire on a postback without a subsequent call to oGrid_Sorting(). Depending on how you’re implementing state, this could mean the list switches back to being unsorted – giving the impression of duplicating or missing out entries if you sort before you page, so to speak.