Partilhar via


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;
        oGrid.AllowPaging = true;
        oGrid.PageIndexChanging += 
            new GridViewPageEventHandler(oGrid_PageIndexChanging);
        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;
            oGrid.DataBind();
        }

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.

 Enjoy.

Comments

  • Anonymous
    May 14, 2007
    Great news everyone o/ - a solution to setting an SPGridView filter has been researched and documented

  • Anonymous
    May 29, 2007
    This has been a great post - thanks

  • Anonymous
    June 01, 2007
    This has been the BEST post on using SPGridView so far. Thank you Paul!

  • Anonymous
    July 01, 2007
    Hi 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 ? Thanks

  • Anonymous
    July 01, 2007
    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?

  • Anonymous
    July 02, 2007
    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 ? Thanks

  • Anonymous
    July 02, 2007
    The comment has been removed

  • Anonymous
    July 03, 2007
    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 ?

  • Anonymous
    July 03, 2007
    P.S also tried colMenu.TextFormat = "{0}<br>{1},  Size:{2} {3}";

  • Anonymous
    July 03, 2007
    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.

  • Anonymous
    July 05, 2007
    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 ? Cheers

  • Anonymous
    July 05, 2007
    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?

  • Anonymous
    July 06, 2007
    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

  • Anonymous
    July 31, 2007
    It is a great posting so far.

  • Anonymous
    August 08, 2007
    Currently I&#39;m busy with redeveloping some &#39;old&#39; 2003 webparts and quite often I used a .NET

  • Anonymous
    September 17, 2007
    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?

  • Anonymous
    December 11, 2007
    Hi 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

  • Anonymous
    December 28, 2007
    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.

  • Anonymous
    March 03, 2008
    Can u send me the complete source code ? regards

  • Anonymous
    March 27, 2008
    Hi, 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.

  • Anonymous
    May 13, 2008
    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?

  • Anonymous
    June 06, 2008
    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 http://ketulpatel.wordpress.com/2008/06/06/custom-paging-in-spgridview-extending-spgridviewpager/

  • Anonymous
    August 21, 2008
    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 :-) http://www.sharepointblogs.com/wirkus/archive/2008/08/21/how-to-professionelle-datenanzeige-mit-dem-control-spgridview.aspx

  • Anonymous
    September 23, 2008
    Nie raz już w różnych przypadkach podawałem wam linki odnoszące się do SPGridView , pora się temu trochę

  • Anonymous
    November 25, 2008
    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?

  • Anonymous
    February 05, 2009
    Hi, 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?

  • Anonymous
    February 09, 2009
    The comment has been removed

  • Anonymous
    June 23, 2009
    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?