0

I am working on an Event Receiver for my SharePoint farm 2013. now i have a site column of type "People or Group", and this site column can hold User Name/s OR group names.

so inside my Event Receiver code, i want to check for the item type an based on it assign the site column to a varaible as follow:-

 SPListItem currentItem = properties.ListItem;

 string initial = "";
 SPUser orderOwner = null; 
       if (currentItem.ContentType.Name.ToLower().Contains("p"))
          {
              initial = "P";
              orderOwner = currentItem["ProjectOwner"] != null ? (SPUser) currentItem["ProjectOwner"] : null;
           }
       else if (currentItem.ContentType.Name.ToLower().Contains("s"))
          {
                initial = "S";
                orderOwner = currentItem["SalesOwner"] != null ? (SPUser)currentItem["SalesOwner"] : null;
          }
       else if (currentItem.ContentType.Name.ToLower().Contains("c"))
          {
                  initial = "C";
                  orderOwner = currentItem["CancellationOwner"] != null ? (SPUser)currentItem["CancellationOwner"] : null;
          }

now my above code will work as long as the orderOwner variable is holding an SPUser, but if the related field (ProjectOwner,SalesOwner,CancellaltionOwner) is holding an SPGroup my code will break. so i am not sure how i can have a variable type inside my Event Reciever, which can hold an SPUser or SPGroup ??

2

You can identify whether the value contains a user or a group by following piece of code:

SPUser user = null; SPGroup group = null;
var userField = (SPFieldUser)currentItem.Fields.GetField("ProjectOwner");
var userFieldValue = (SPFieldUserValue)userField.GetFieldValue(currentItem["ProjectOwner"].ToString());

// This means the value contains a USER
if (userFieldValue.User != null)
{
    user = userFieldValue.User;
}
else //otherwise the value contains a group
{
    group = web.SiteGroups.GetByID(userFieldValue.LookupId);
}

Than check which one is not null and use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.