in

Corey Roth and Friends Blogs

Group site for developer blogs dealing with (usually) Ionic, .NET, SharePoint, Office 365, Mobile Development, and other Microsoft products, as well as some discussion of general programming related concepts.

Kyle Kelin on .Net

Method Ordering Constraint with the SPGridView

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:

  1. Instantiate the GridView.
  2. Set the properties and the datasource.
  3. Add the Gridview control to the ChildControls Collection
  4. Set the PagerTemplate to null
  5. 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.

Comments

 

Chuck Tayywick said:

Hi Kyle:

Thanks for this.  Spent a whole day trying to figure out why i was not getting page icons on my SPGRidView web part.

I agree with you that this is a bug.  Normally you define all the properties and attribtes on a control before you instantiate and or add it.

Thanks again

Chuck

July 9, 2008 5:32 AM

Leave a Comment

(required)
(optional)
(required)
Add

About KyleKelin

Kyle Kelin has been implementing software in the Microsoft space for the past 6 years mainly as a consultant. His interests are SharePoint, .NET, JQuery, and Silverlight.
2019.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems