Logo 
Search:

Sharepoint Forum

Ask Question   UnAnswered
Home » Forum » Sharepoint       RSS Feeds

Creating Lookup Fields Programmatically

  Asked By: Eve    Date: Nov 05    Category: Sharepoint    Views: 3322

I'm trying to use some code that I found that allows for the
creation of Lookup fields programmatically, and then using it in a
Feature. The issue is that it errors out intermittently. Below find
the method, the line that calls it, and then the error. There's no
compile issues, nothing crazy, and it's really bugging me because it
works sometimes. Any thoughts? I'd really appreciate it. Thanks! - M

Method
public static SPFieldLookup CreateLookupField(string fieldName, string
group, bool required, bool allowMultipleValues, SPWeb w, SPList
lookupList, string lookupField)
{
w.Fields.AddLookup(fieldName, lookupList.ID, lookupList.ParentWeb.ID,
required);
SPFieldLookup lookup = (SPFieldLookup)w.Fields[fieldName];
lookup.AllowMultipleValues = allowMultipleValues;
lookup.LookupField = lookupField;
lookup.Group = group;
lookup.Update(true);
return lookup;
}

Code calling method
SPFieldLookup lookup = CreateLookupField("Department", "Project Custom
Site Columns Group", true, false, SPContext.Current.Site.RootWeb,
SPContext.Current.Site.RootWeb.Lists["Department List"], "Title");

Error
Feature Activation: Threw an exception, attempting to roll back.
Feature 'SiteInfrastructure' (ID:
'd1bb0290-8290-4508-a5d9-5df7e7cddda7'). Exception:
System.InvalidCastException: Unable to cast object of type
'Microsoft.SharePoint.SPFieldText' to type
'Microsoft.SharePoint.SPFieldLookup'. at
SiteInfrastructure.FeatureReceiver.CreateLookupField(String fieldName,
String group, Boolean required, Boolean allowMultipleValues, SPWeb w,
SPList lookupList, String lookupField)...

Share: 

 

No Answers Found. Be the First, To Post Answer.

 
Didn't find what you were looking for? Find more on Creating Lookup Fields Programmatically Or get search suggestion and latest updates.