Wednesday, May 5, 2010

SharePoint List’s Person or Group field value as c# SPUser objet

Casting the list's Person or Group field value into SPUser object.
using(SPSite spSite = new SPSite("site URL"))
{
   using(SPWeb spWeb = spSite.OpenWeb())
   {
      SPList spList = spWeb.Lists["List Name"];
      SPListItem spListItem = spList.GetItemByID(itemID);
      string currentValue = spListItem["Person or Group field name"].ToString();
     SPFieldUser userField = (SPFieldUser)spWeb.Lists["List Name"].Fields.GetField("Person or Group field name");
     SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(currentValue);
     SPUser user = fieldValue.User;

                                          OR

     SPFieldUserValue spFieldUserValue = new SPFieldUserValue(web ,  Convert.ToString(projectItem["Person or Group field name"]));
     SPUser user =  spFieldUserValue.User;
   }
}

4 comments:

  1. Can you please tell me what does the itemID mean in spList.GetItemByID(itemID)...?

    ReplyDelete
    Replies
    1. or would you please tell me how to use Current Item ID in that place..??

      Delete
  2. hi,
    is it possible to access the person column from a root site collection 's splist within my itemupdated event receiver?. my item event receiver updated event is fired within a subsite's doclib. when a user uploads the document it fires this itemupdated eventreceiver and tried to access the root site collection's splist column which is person or group.
    but i am getting the error : value doesnt fall within the excepcected range.
    pls help how to resolve this.

    ReplyDelete