Dynamic GridView Paging Issue – NullReferenceException

Today I ran into a very strange situation with the ASP.NET 2.0 GridView control.   I was creating a SharePoint 2007 web part which consisted of a gridview control which was being dynamically created during the CreateChildControls method of the web part.    The gridview was being added to the web part’s control collection after the DataBind method was called on the gridview.   Everything was displaying correctly until I turned on paging for the gridview.   Once paging was turned on I started receiving a NullReferenceException error.   I used VS.NET to debug the web part and found that the error was being thrown as soon as the DataBind method was called.     In the stack trace of the error I noticed that the last entry referenced a method called BuildCallbackArgument(Int32 pageIndex).    I did a few searches on the net and came up with no information that was usefull on that method or on the error I was seeing.
I finally was able to track down the problem.  It appears that the gridview needs to be added to a controls collection prior to calling the DataBind method.   I modified my code so that immediately after creating the gridview control I added it to the web part’s control collection.  Once I did that the web part worked as expected and the gridview displayed properly.  

0 thoughts on “Dynamic GridView Paging Issue – NullReferenceException”

  1. Thanks so much!!  I””ve only spent a couple of days trying to figure out this problem, but you just saved me a few more days.  And, all it took was to move one line of code!

Leave a Reply