Friday, November 27, 2009

How to: Converting List Item to SPUser object

Hi All, 

Many times we need to cast a list item to a SPUser object. It can easily done using these steps: 

Step1: Get the current item
SPListItem currentItem = properties.ListItem; 

Step2: Get the value display name of the current logged in user and Created by Field of the current item
currentUser = currentItem["Author"].ToString();

Step3: Get the user id as integer
int userid = Convert.ToInt32(currentUser.Substring(0, currentUser.IndexOf(";#")));

Step4: Convert SharePoint user which matches the ID
SPUser user = currentTeamSite.AllUsers.GetByID(userid);

There is one more case where we have number of users. In this scenario, 
we can loop the users: 

--------------------------------------------------------------------------------
// get a reference to the "Alerts" list as an instance
 SPList alerts = spWebRoot.Lists["Checklists Alerts"];
 
// get the query object for user alert
 SPQuery queryUserAlert = new SPQuery();
 
queryUserAlert.Query = "<Where>" +
      "<Eq>" +
               "<FieldRef Name='Team' />" +
               "<Value Type='Choice'>" +    teamName + "</Value>" +
       "</Eq>" +
 "</Where>";

 SPListItemCollection noOfUsers = alerts.GetItems(queryUserAlert);

//Get all the users in that team (such as Desktop Support - Daily)
foreach (SPListItem item in noOfUsers)
 {
        //Use "GetUser" function for List "item" into a SPUser ojbect 
        SPUser user = GetUser(item, item.Fields["User"]);

        // REMAINING LOGIC


private SPUser GetUser(SPListItem item, SPField userField)
 {
     string currentValue = item[userField.Title].ToString();
     SPFieldUser field = (SPFieldUser)userField;
     SPFieldUserValue fieldValue = (SPFieldUserValue)field.GetFieldValue(currentValue);
      return fieldValue.User;

  }

Happy programming, 

Cheers
--Aroh 

No comments:

How to display Sharegate administrative dynamic reports via Power BI on SharePoint Online

After working in the SharePoint domain for a couple of years as SharePoint consultant , I am fortunate enough to help customers from man...