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 an ItemAdded event handler connected to a document library, in order to automatically populate certain fields when a new document is uploaded:

public class AutoPopulateDocumentFields : SPItemEventReceiver
{
   public override void ItemAdded(SPItemEventProperties properties)
   {
       base.ItemAdded(properties);

       SPList sourceList = properties.List;

       sourceList["Title"] = "Auto-populated title value";

        try {
            this.EventFiringEnabled = false;
            sourceList.Update();
        }
        finally {
            this.EventFiringEnabled = true;
        }
   }
}

This usually works when uploading a new file. I get an intermittent error, though: Sometimes the update list item form which shows up after upload does not have the "Title" field autofilled, and when clicking "OK" I get the error message

The file "Documents\testfile.txt" was changed by Geir Smestad on the 18. Nov 2011 11:28:47 +0100

This is a SharePoint error, not an error in my code. After closing the error, the Title has the value "Auto-populated title value" but all other fields have their default values. What is wrong?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

This is caused by a race condition in the version control system. Events are as follows:

1. Your file finished uploading
2. Your event handler code runs (in a different thread)
3. The update list item form is populated and displayed
4. You click OK in the update list item form and the changes are submitted

Since ItemAdded is asynchronous, sometimes your event handler code doesn't have time to finish executing before the Update List Item form is loaded. Therefore, the Update List Item form is populated with the old version of the file's columns. When clicking OK (and your code has already had time to save the new version of the file), SharePoint attempts to submit the old version of the file, resulting in an error.

To solve the problem, call sourceList.SystemUpdate(false) instead of Update(), which updates the file without incrementing the version number.

share|improve this answer

Instead of properties.List use properties.ListItem as below,

SPList sourceListItem = properties.ListItem;

sourceListItem["Title"] = "Auto-populated title value";

sourceListItem.SystemUpdate(false);
share|improve this answer

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.