SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a custom list, where when I create a new item, I assign a custom id to that element through an event receiver. After the item is created, I create a file that I upload to a document library. This document is supposed to be connected to the custom list through a lookupfield. The lookupfield is the same as the custom id i created on itemadded.

When i upload the file I am able to set all the fields, except the lookupfield. How can i select a specific lookupvalue for my document?

The event receiver is bound to a specific list with <Receivers ListUrl="Lists/CustomList">

This is how i update the item on ItemAdded.

public override void ItemAdded(SPItemEventProperties properties)
    SPListItem element = properties.ListItem;
    //Just to set my custom value
    int itemId = properties.ListItemId;
    int customId = itemId+10000;
    element["Title"] = customId;


In the same eventreceiver,within the ItemAdded method, I do the following to upload the document and set its values:

SPSite site = new SPSite("http://localhost");
        SPWeb web = site.OpenWeb();
        web.AllowUnsafeUpdates = true;
        SPFolder Documentlibrary = web.Folders["Documentlibrary"];
        Boolean replaceExistingFiles = true;
        String filename = "C:\\files\\" + customId + ".jpeg";
        String name = customId+ ".jpeg";
        FileStream upload= File.OpenRead(filename);
        SPFile spfile = Documentlibrary.Files.Add(name, upload, replaceExistingFiles);

        SPList docAsList = web.Lists["Documentlibrary"];
        SPListItem itemJustAdded = docAsList.GetItemById(spfile.ListItemAllFields.ID);
        itemJustAdded["Title"]= customId;            
        itemJustAdded["Cat"] = "cat1";
        //This here is the lookupvalue I want to set.
        itemJustAdded["CustomID"] = customId;

        web.AllowUnsafeUpdates = false;

Ok, so I'm guessing that the issue is with my assignment in the line: itemJustAdded["CustomID"] = customId; However I don't know how to select the correct value, could i use element.ID for example?

Im really hoping someone can shed some light on this for me, maybe some best practice. Thanks in advance.

share|improve this question
up vote 1 down vote accepted

If you want to set a SPFieldLookupValue you have to create one first and then you can set this in your item field.

Like this:

SPFieldLookupValue newValue = new SPFieldLookupValue(itemId,customId);
itemJustAdded["CustomID"] = newValue;
share|improve this answer
Thank you very much! This did it for me! – Alexander Oct 18 '13 at 11:24

Your Answer


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.