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
The below code to gets SPUser from User or Group field in the list
Multiple choice X
Groups X
//get SPUser
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
SPUser user = userFieldValue.User;
Multiple choice Y
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
SPUser user = userFieldValue.User;
Multiple choice Y
Groups X
//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);
}
Group Y
//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);
}
//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);
}
Group Y
//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);
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.