You have person or group field in SharePoint list and you want to programmatically get the user or person.
The below code to gets SPUser from User or Group field in the list when multiple choice and Groups are not allowed in the field:
//get SPUser
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
SPUser user = userFieldValue.User;
This part of code would help you to get SPUser when multiple choice is allowed and groups are not allowed:
//Multiple choices are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValueCollection userFieldValueCollection = (SPFieldUserValueCollection)userField.GetFieldValue(item["Users"].ToString());
foreach (SPFieldUserValue userFieldValue in userFieldValueCollection)
{
Console.WriteLine(" " + userFieldValue.User.LoginName);
}
And when group is allowed. The below code to gets group
//Group or User are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
//Tries to get SPUser
if (userFieldValue.User != null)
{
SPUser user = userFieldValue.User;
}
//if the field contain group
else
{
SPGroup group = web.SiteGroups.GetByID(userFieldValue.LookupId);
}
The below code to gets SPUser from User or Group field in the list when multiple choice and Groups are not allowed in the field:
//get SPUser
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
SPUser user = userFieldValue.User;
This part of code would help you to get SPUser when multiple choice is allowed and groups are not allowed:
//Multiple choices are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValueCollection userFieldValueCollection = (SPFieldUserValueCollection)userField.GetFieldValue(item["Users"].ToString());
foreach (SPFieldUserValue userFieldValue in userFieldValueCollection)
{
Console.WriteLine(" " + userFieldValue.User.LoginName);
}
And when group is allowed. The below code to gets group
//Group or User are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
//Tries to get SPUser
if (userFieldValue.User != null)
{
SPUser user = userFieldValue.User;
}
//if the field contain group
else
{
SPGroup group = web.SiteGroups.GetByID(userFieldValue.LookupId);
}
But It always give me an error
ReplyDeleteUnable to cast object of type 'Microsoft.SharePoint.SPFieldText' to type 'Microsoft.SharePoint.SPFieldUser'.