Pages

Thursday, February 13, 2014

Retrieve Author of SPListItem as SPUser in SharePoint; programmatically (C#)

Introduction
Updated on 15th July 2014

I was assigned in a project where I had to retrieve the author of the SPListItem as SPUser programmatically.

Solutions

In these solutions I’m returning the login name. But you can get the SPUser.

Solution 01

  1. public string GetListItemAuthorNameSPBuiltInFieldId(SPListItem spListItem)
  2.       {
  3.           string loginName = string.Empty;
  4.           SPWeb spWeb = SPContext.Current.Web;
  5.  
  6.           var fullUserName = spListItem[SPBuiltInFieldId.Author] as string;
  7.           var userName = fullUserName.Split('#')[1];//This is only to get the user name. My fullUserName was 1;#Setup Admin.
  8.           SPUser spUser = spWeb.EnsureUser(userName);//You can get SPUser from here
  9.           loginName = spUser.LoginName;
  10.           return loginName;
  11.  
  12.       }
It is recommended to SPBuiltInFieldId in order to retrieve build in fields.

Solution 02

  1. public string GetListItemAuthorName(SPListItem spListItem)
  2.   {
  3.       string loginName = string.Empty;
  4.       var spFieldUser = spListItem.Fields.GetFieldByInternalName("Author") as SPFieldUser;
  5.  
  6.       if (spFieldUser != null && spListItem["Author"] != null)
  7.       {
  8.           var fieldValue = spFieldUser.GetFieldValue(spListItem["Author"].ToString()) as SPFieldUserValue;
  9.           if (fieldValue != null)
  10.           {
  11.               var spUser = fieldValue.User;//Get the SPUser
  12.               loginName = spUser.LoginName;//Get the login name from SPUser
  13.           }
  14.       }
  15.       return loginName;
  16.   }


Conclusion

I will update how to retrieve values from SPField in future days.

4 comments: