SPGridView: Adding paging to SharePoint when using custom data sources

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:

 SPGridview showing paging controls

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;
= true;
new GridViewPageEventHandler(oGrid_PageIndexChanging);
= 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)
= 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.


Comments (28)

  1. Great news everyone o/ – a solution to setting an SPGridView filter has been researched and documented

  2. RobertaRuane says:

    This has been a great post – thanks

  3. ArjunaK says:

    This has been the BEST post on using SPGridView so far.

    Thank you Paul!

  4. Brian111 says:


    Got this working fine. However when I put a button on the web part to fire off the create dataset bit the first page of the results are returned fine but if I then select another page the results control disappears completely. Any ideas ?


  5. Paul Robinson says:

    sounds like an issue with the page lifecycle – is it possible you dont initialise the control properly on the callback, or dont persist the state?

  6. Brian111 says:

    Yes, thanks you were absolutly right.

    On a slightly different but related subject when the CreateChildControls has a conditional set of contols on it. ie either search criteria or search results. When these are switched I am getting an error "unexpected error has occurred". I have found that whenever I add contols to the web part I need to manually change the size of the web part in the web part properties in sharepoint.

    Do you know why this occurs ?


  7. Paul Robinson says:

    sounds bizarre.  off-teh-top-of-my-head I’d be thinking that changing the size is one way to invalidate the cache.  Perhaps your caching is configured such that MOSS doesn’t recognise the new control has been added?  Just a thought.

  8. Brian111 says:

    In the menu field I have been trying to add more than one TextField and then format it appropriatly. This works fine except I can not force a carriage return between the fields. You can see how I am trying to do this below…

    colMenu.TextFields = "DAV:displayname, DAV:href, Size, HitHighlightedSummary";

    colMenu.TextFormat = "{0} n {1}, Size:{2} rn {3}";

    Do you know if it is possible ?

  9. Brian111 says:

    P.S also tried

    colMenu.TextFormat = "{0}<br>{1},  Size:{2} {3}";

  10. Paul Robinson says:

    Umm – when I saw you’d tried rn I thought I’d recommend <br> – but apparently not!  Good luck – please post if you find the answer.

  11. Brian111 says:

    Nope never managed to solve this, It seems to take out all html coding as if using SPEncode.

    Had to go back to the beginning, drop the SPGridView and biuld the results in a table. Shame as I also have to code all the paging now as well.

    Still got one problem and that is it will only return up to 10 results ! Any idea why this would be. Is there a setting somewhere ?


  12. Paul Robinson says:

    Oh dear dear. We can’t have you resorting to tables when there’s a lovely SPGridView. This will not stand Brian!  I’ll take a look this weekend – it must be possible, right?

  13. Brian111 says:

    Thanks, away next week so no rush and finished solution now but would be good to know for future. It beat me if it is possible ! Cheers

  14. shandao_song@hotmail.com says:

    It is a great posting so far.

  15. Currently I&#39;m busy with redeveloping some &#39;old&#39; 2003 webparts and quite often I used a .NET

  16. jordoman says:

    Thanks for a very useful post. I’m having trouble creating a PagerTemplate though. Rather than a few insignificant looking numbers at the bottom of the grid it would be nice to have links kind of like:

    First Prev 1 2 3 4 5 Next Last

    Do you think you might have time to update with a small example?

  17. divya028 says:


    When i use SPGridView its throws error as " Object reference not set to an instance of an object ".

    But if i use Datagrid it has no issues. i dont want to use datagrid since paging is not happening in it properly. kindly help

  18. ArunDutt says:

    Hello Paul,

    Thank you for the nice article. I’ve tried your code and it is working. But I have a problem with the paging. I enabled the paging for the SPGridView, but the problem is the pager buttons are not visible. I really dont know what the problem is.

  19. sberger75 says:

    Can u send me the complete source code ?


  20. JayZeh says:


    I’m also having some problems displaying the buttons.

    Were you guys able to solve this problem?

    Ive created a spgridview and put it on a table cell,

    the item counts are rendering properly but no paging links.

  21. lpmeunier@msn.com says:

    Anyone was able to find a solution to the paging buttons not displayed?

    I followed this article series using the SPGridView and so far everything has worked pretty well, but i can’t seem to be able to get those paging links to show up. The item limit per page does work though, just not the paging links.

    Any ideas?

  22. pateketu says:

    Good post helped me get on with Paging in SPGridView, but I wanted more custom paging style like "Page 1 of 10".

    Found a solution to do that by extending SPGridViewPager


  23. Oliver Wirkus says:

    Excellent article, Powlo – good job!

    I took the infos you posted here to build an example on how to use SPGridView with sorting, paging and filtering. I was able to display the sorting-icon and filtering-icon just like we know it from sharepoint lists.

    Here is the link – just in case someone is interessted 🙂


  24. Nie raz już w różnych przypadkach podawałem wam linki odnoszące się do SPGridView , pora się temu trochę

  25. abis123 says:

    Excellent blog and article. Got to be my main source of SPGridView information on the web.

    Quick question, if I apply paging and write out a count of results it only displays the amount per page (not total results). Do you know a way to return a count of all results with paging activated?

  26. vmoroz says:


    I have built the web part with grouping an paging. The paging works just fine. But I have an issue. If I collapse the last group in last page the pager control disappears together with group rows. This is confusing our portal users. Does someone know how to let pager navigation stays on the bottom of page when last group is collapsed?

  27. lzandman says:

    Above I read that some users have problems with their paging buttons (they don’t appear). A cause for this might be that the line where you set the PagerTemplate to null is in the wrong position.

    It needs to be executed AFTER the grid has been added to the Controls collection of its parent control. If this parent control itself is also contained in a control (as is often the case with composite controls), then you have to place the line with the PagerTemplate assignment after all those calls.


    SPGridView _grid = new SPGridView();

    Panel _panel = new Panel();



    _grid.PagerTemplate = null;

  28. bilalfastian says:

    Thanks for the nice Post.

    I am have a problem that, every thing renders properly first time data is bound, but as soon as I change the page, data still renders correctly but the alignment of first column is disturbed. It sticks to the left margin of Grid once I navigate from the first page. Even going back to first page does not restore it.

    My first column is a template field. I am not using any alignment related property with template field.

    Any suggestions?

Skip to main content