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>" +

 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"]);


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, 


No comments:

How to: Power Apps with Azure SQL Server

Hi All, In Jan 2020 SQL PASS Meetup I spoke on how to use Power Apps with data in  Azure SQL Server. SQL Meetup link Slide Deck  for h...