Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am creating a custom list programmatically. List has one Lookup field. Here is my code sample how I am creating LookUp field.

 oList.Fields.AddLookup("Parent", oListGuid, false);                  
 SPFieldLookup fldLookUp = (SPFieldLookup)oList.Fields["Parent"];
 fldLookUp.LookupField = oList.Fields["Parent"].InternalName;           
 fldLookUp.Update();

 SPFieldLookupValueCollection lkpValues = new SPFieldLookupValueCollection();
 lkpValues.Add(new SPFieldLookupValue(0,"None"));
 lkpValues.Add(new SPFieldLookupValue(1, "Parent1"));
 lkpValues.Add(new SPFieldLookupValue(0, "Parent2"));

I am not sure how to assign value collection to my look up field.

I tried something like oListItem["Parent"]=lkpValues ;

But it gives me an error

Error occurred in deployment step 'Activate Features': Invalid data has been used to update the list item. The field you are trying to update may be read only.

Please help me on this.

Regards VB

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Correct me if I'm just being stupid, but isn't the point of the lookup field to pull data from another list?

That being the case you should be adding data to the list your lookup is attached to (which should not your current field)....

Taken from http://sarangasl.blogspot.com/2009/11/add-lookup-column-to-sharepoint-list.html:

SPList newList = web.Lists["New List"];
SPList targetList = web.Lists["Target List"];

newList.Fields.AddLookup("Lookup Column", targetList.ID, false);
SPFieldLookup lkp = (SPFieldLookup)newList.Fields["Lookup Column"];
lkp.LookupField = targetList.Fields["Title"].InternalName;
lkp.Update();

Following this just add items to the targetList list and you sould be good to go.

share|improve this answer
    
Yes your are right.Thanks –  V.B Jun 11 '12 at 6:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.