I was a working on a web part this week that was to display a list of users. The requirements evolved to include paging so I decided to use a SPGridView. But when I set the AllowPaging property to true I would get the following exception: object reference not set to an instance of an object. After spending some significant time digging around on Google I found the answer. The answer lies in the order of the API calls. You have to set the PagerTemplate to null after you add the GridView control to the ChildControls collection but before you bind the control.
So my code in RenderContents does the following in order:
- Instantiate the GridView.
- Set the properties and the datasource.
- Add the Gridview control to the ChildControls Collection
- Set the PagerTemplate to null
- Bind the control
My Code:
usersGrid = new
SPGridView();
usersGrid.ID = "usersGrid";
usersGrid.AutoGenerateColumns = false;
usersGrid.PageIndexChanging += new
GridViewPageEventHandler(usersGrid_PageIndexChanging);
usersGrid.DataSource = usersCollection;
this.Controls.Add(usersGrid);
usersGrid.PagerTemplate = null;
usersGrid.DataBind();
I imagine the reason for this has to do with the page life cycle but I don't know the exact reason. The first one that posts the answer in the comments gets a free DotNetMafia T-Shirt. Also in my opinion this is a design flaw. You should avoid ordering constraints for a method call and if that restraint is required than the exception throw should do a better job of indicating the constraint.
Note: I have not tested whether or not you would get this same behavior with a GridView on a normal web page.