Question

I've got an EventReceiver in my SharePoint application where I'm overriding ItemAdding and ItemUpdating methods:

public override void ItemAdding(SPItemEventProperties properties)
{
   SPWeb web = properties.OpenWeb();

   switch (properties.ListTitle)
   {
        //some cases

        case "Employees":
            if (properties.AfterProperties["User"] != null)
            {
               SPUser user = web.SiteUsers
               [
                   properties.AfterProperties["User"].ToString().Substring
                   (
                        properties.AfterProperties["User"].ToString().IndexOf(";#") + 2
                    )
               ];

               properties.AfterProperties["Title"] = user.Name;
            }
            break;
   }

   base.ItemAdding(properties);
}

Code in both methods is exactly the same. But sometimes Title field remains empty after adding an item to list. And if I update that item (without any changes) Title field is filled by username correctly.

No correct solution

OTHER TIPS

I see two potential issues in your code:

  1. processing properties.AfterProperties["User"] by parsing it. It would be better to use code like this (SPUserFieldValue)properties.ListItem.Fields["User"].GetFieldValue(properties.properties.AfterProperties["User"].ToString()). This way suggested by MSDN.
  2. Using SiteUsers indexer throws Exception when user is not found in the collection. You should wrap it by try ... catch statement. It can happen when user is used for the first time in your site collection.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top