Categories
Coding

Value does not fall within the expected range

The following code, which was supposed to update the “Current” Composed Look, was throwing a “value does not fall within the expected range” error each time I ran it.

SPWeb web = properties.Feature.Parent as SPWeb;
SPList gallery = web.GetCatalog(SPListTemplateType.DesignCatalog);

if (gallery != null)
{
    SPQuery q = new SPQuery();
    q.RowLimit = 1;
    q.Query = "<Where><Eq><FieldRef Name='DisplayOrder'/><Value Type='Number'>0</Value></Eq></Where>";
    q.ViewFields = "<FieldRef Name='DisplayOrder'/>";
    q.ViewFieldsOnly = true;

    SPListItemCollection items = gallery.GetItems(q);

    foreach (SPListItem item in items)
    {
        item["MasterPageUrl"] = web.MasterUrl;
        item.Update();
    }

}

After a lot of head scratching, it boiled down to the ViewFieldsOnly property which, which I had left set to true. Doh! Updating the property to false corrected the error.

See: SPQuery.ViewFieldsOnly property