We are using different types of fields when working with SharePoint applications.
One of an important type among them is Person or Group field which is manage user values in site contents. This post has described that how to work with Person or Group field programmatically.
One of an important type among them is Person or Group field which is manage user values in site contents. This post has described that how to work with Person or Group field programmatically.
1. Get SPUser from
Person 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;
//Get SPUser
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
SPUser user = userFieldValue.User;
2. 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);
}
3. Get
SPUser when group is 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);
}
//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