0

I've currently got a new task list item for a certain content type (DMR) which fails to take through the lookup to the associated list. The statement prints the correct record number in the immediates window but doesn't take the value through. The task list has the newly created item available as a lookup on edit so I'm confused as to what the problem is as all other fields are set when the code is executed.

Here's the coding:

//gets the current list item
SPListItem oCurrent = properties.ListItem;

//create a new task containing a lookup to the current item
SPList olstRegisterTasks = oCurrent.Web.Lists["Register Tasks"]; 
SPListItem oTask = olstRegisterTasks.Items.Add();

//other fields that work as aspected..
//the next line doesn't assign
oTask["Related DMR"] = new SPFieldLookupValue(oCurrent["DMR No."].ToString()).LookupId;

oTask.Update();

1 Answer 1

0

LookUp Field Values are stored in format (ID);#(VALUE)

You can use below line of code

SPFieldLookup lookUpField = (SPFieldLookup)myList.Fields["DMR No."];
SPList lookupSourceList = myList.ParentWeb.Lists[lookUpField.LookupList];

SPQuery query = new Microsoft.SharePoint.SPQuery();
query.Query = String.Format("{0}", lookupValue);
SPListItemCollection listItems = lookupSourceList.GetItems(query);

oTask["Related DMR"] = new SPFieldLookupValue(listItems[0].ID.ToString());

How to set a lookup field by c# code

4
  • but the output of the lookup id when I run the statement gives the exact string so theres none of the ';#val' included
    – Matt
    Nov 26, 2014 at 15:02
  • @Matt in the code you are assigning LookupId instead of the SPFieldLookupValue object Nov 26, 2014 at 15:04
  • im assigning the lookup id of the spfieldlookupvalue. However, I did try both earlier and didnt make a difference. In the list I just want a lookup to that list item
    – Matt
    Nov 26, 2014 at 15:10
  • followed the link and it works. I'd previously done that adding an id and it hadn't changed anything but thankfully its all good cheers
    – Matt
    Nov 26, 2014 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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