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
- public string GetListItemAuthorNameSPBuiltInFieldId(SPListItem spListItem)
- {
- string loginName = string.Empty;
- SPWeb spWeb = SPContext.Current.Web;
- var fullUserName = spListItem[SPBuiltInFieldId.Author] as string;
- var userName = fullUserName.Split('#')[1];//This is only to get the user name. My fullUserName was 1;#Setup Admin.
- SPUser spUser = spWeb.EnsureUser(userName);//You can get SPUser from here
- loginName = spUser.LoginName;
- return loginName;
- }
Solution 02
- public string GetListItemAuthorName(SPListItem spListItem)
- {
- string loginName = string.Empty;
- var spFieldUser = spListItem.Fields.GetFieldByInternalName("Author") as SPFieldUser;
- if (spFieldUser != null && spListItem["Author"] != null)
- {
- var fieldValue = spFieldUser.GetFieldValue(spListItem["Author"].ToString()) as SPFieldUserValue;
- if (fieldValue != null)
- {
- var spUser = fieldValue.User;//Get the SPUser
- loginName = spUser.LoginName;//Get the login name from SPUser
- }
- }
- return loginName;
- }
A much better way is to use SPBuiltInFieldId!
ReplyDeleteThank you very much. Updated accordingly.
DeleteMany Thanks, very useful to me.
ReplyDeleteU r welcome :)
Delete