Wednesday, 21 December 2011

The Straw That Broke the CAML's back: Manipulating Content Type field in a view

This post will be brief. I wish my discovery had been so too!

Let's say you create an SPQuery object from the default view of a list. Then you deploy your query, putting the result into an SPItemCollection object. That done, you want to determine a certain sequence of events based on the content type of the specific item when looping through the collection.

So, trying various methods in vain:

SPQuery query = new SPQuery()
SPListItemCollection items = list.GetItems(query);

foreach (SPListItem item in items)
    if (item.ContentType.Name == "This line will throw an error)
        //this condition never gets hit
    if (item["ContentType"].ToString() == "So will this one")
        //this one doesn't either
    if (item.ContentType.ID == "you get the idea blah blah"


Kept getting "Cannot complete this action", "object not set to instance of an object", and when I tried Content Type ID some exception that had HRESULTS and big long hexy number and god knows what.

Then I thought - the view I ran the query from - I did display the content type on that - didn't I? I went in and ticked the ContentType field in the view so that it was visible?

Nope. I didn't. So it couldn't find it. D'oh! I hope reading this saves you the trouble I got into!

No comments:

Post a Comment