Skip to main content

Cloud

Creating a lookup site column in SharePoint programmatically using the object model

Provisioning lookup site columns cannot be done through CAML alone. I have seen claims that it could be done (see http://blogs.msdn.com/joshuag/archive/2008/03/14/add-sharepoint-lookup-column-declaratively-through-caml-xml.aspx) but I was never able to make it work when the column to lookup is not “Title” or when it resides on the list in a different SPWeb.

I also saw methdos on the web that suggeest a combination of CAML and an object model but they seem akward and somewhat kludgy (see http://www.sharepointblogs.com/tmt/archive/2007/09/06/sharepoint-programmatically-provisioning-lookup-fields.aspx). Although, if you MUST use CAML for whatever reason they are your only choice. Plus they work :).

As far as I am concerned, if you can avoid CAML and use object model in a feature receiver, you are better off since you get normal debugging and no limitations of CAML.

Here is a little helper method I created that creates a lookup column for you:

public static SPFieldLookup CreateLookupSiteColumn(SPWeb web, string fieldName, Guid lookupListGuid, string lookupFieldName, Guid lookupWebGuid)

{

//create a field and save it

string name = web.Fields.AddLookup(fieldName, lookupListGuid, lookupWebGuid, true);

SPFieldLookup lookup = (SPFieldLookup)web.Fields.GetField(name);

lookup.Group = groupName;

lookup.LookupField = lookupFieldName;

lookup.Update();

web.Update();

return lookup;

}

As always, if you see any mistakes or inaccuracies in this blog, please let me know.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

PointBridge Blogs

More from this Author

Follow Us