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 have this script which creates a new site (SPWeb), which is based on a template.

I will the copy the data from the main list into the new list on the new site.

Both list is based on the same Contenttype.

SPList l = createWebsite.Lists["Sags Info"];
SPListItem li = l.Items.Add();
li["Title"]         = properties.ListItem.Title; <-- WORKS FINE
li["LP_Postal"]     = properties.ListItem["LP_Postal"]; <-- WORKS FINE
li["LP_Address"]    = properties.ListItem["LP_Address"]; <-- WORKS FINE
li["LP_Sagstype"]   = properties.ListItem["LP_Sagstype"]; <-- FAILS - Lookup field
li.Update();

How do i copy the lookup field over to the new list?

SPFieldLookup Sagstype = properties.ListItem["LP_Address"];

I have tried this, but that do not seems to work.

share|improve this question
add comment

2 Answers 2

Try to create a SPFieldLookupValue object and assign it to the field value.

share|improve this answer
    
Will the lookup still be preserved this way? –  Kevin Simper Aug 7 '12 at 14:07
1  
It should be, provided the lookup field is created properly. –  NLV Aug 8 '12 at 5:04
    
It did not seems to work for me :/ Could you post an example? That would be really awesome! –  Kevin Simper Aug 14 '12 at 9:36
add comment
up vote 0 down vote accepted

You can set a lookup value by given the id of the item you want to lookup.

So if you are creating a new ListItem you can do like this:

li["MyLookupField"] = "3";

If you try to read a lookupfield it will give you a string like this:

4;#My Value

You can then split this string and simply set your new lookup equal this value.

You can use this code:

string sagsstatuslookup = properties.ListItem["SagsStatus"].ToString();
string[] sagsstatuslookupArray = sagsstatuslookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

li["SagsStatus"] = sagsstatuslookupArray[0].ToString();

The first line creates a new string. Second line creates an array that contains the string which is being splits by the signs ";#".

It will then create an array. First one the number "4", the second the value.

Then assign your new ListItem with that new value.

It is really simple when you first get it and understand how it is put together.

share|improve this answer
add comment

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.