How to get the username from a SPListItem or a SPFieldUser

If you need to get the SPUser object from a SPListItem or from a SPFieldUser you can use the following static method:


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;
}
}

and the usage is:

SPUser objUser = GetSPUser(objListItem,"Owner");
String strUserName = objUser.UserName;

manuel11g

Leave a Reply