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.

1 Answer 1


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;

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.