Clinton's profileCherry BytesBlogListsGuestbookMore Tools Help
    December 05

    Get SPUser object from SPList item

    If you are doing a fair amount of programmatic access to SharePoint lists, you will quickly find there are a number of limitations with the data that is returned in each SPList item object in a SPListItemCollection (what is returned from a SPQuery object). One common problem which I have come across is getting more useful information from a user field (rather than their basic name).

    I recently came across a post on David San Filippo's Blog which addresses this issue with a simple lookup method that he has written. I have included this below as it is a fantastic little piece of code, which gets you some great information about a user, when doing a query (rather than having to loop over the SiteCollection Users or something similar).

    public static SPUser GetSPUser(SPListItem item, string key)
    {
          SPFieldUser field = item.Fields[key] as SPFieldUser; 
    
           if (field != null)
           {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    return fieldValue.User;
                }
           }
          return null;
     }