Question

I've got a content type that contains a filed of the type user. When I want to read the ListItem I just get a string containing the users name instead of a object which contains Name, Username, E-Mail and so on. Is there a way to cast the ListItem-Field to a object or to access the child attributs?

My Code:

var t =   web.Lists[properties.ListId].Items.GetItemById(properties.ListItemId);
var username = t["Administrator"].ToString();
var username2 = (SPUser)t["Administrator"]; //Does not work
var username3 = t["Administrator"];
Was it helpful?

Solution

Assuming that you already have a reference to the list item (called "item" in the following code sample), you must first get a reference to the list field and then use the GetFieldValue method to read the actual value.

SPFieldUser userField= (SPFieldUser)item.ParentList.Fields.GetFieldByInternalName(internalName);
var fieldValue = ((SPFieldUserValue)userField.GetFieldValue((string)item[userField.InternalName]));

Note: the SPFieldUserValue class is a wrapper, the property "User" contains a reference to the actual SPUser. Also notice that my sample uses the internal name to access the field, you can change it to use the ID if you need to.

OTHER TIPS

Shorter way of getting SPUser from the field is

var t = web.Lists[properties.ListId].Items.GetItemById(properties.ListItemId);    
var username = new SPFieldUserValue(web, t["Administrator"].ToString()).User.Name;

To get the item owner detail (Userfield column value) using C#

using(SPSite site = new SPSite("url"))
            {
               using( SPWeb web = site.OpenWeb())
               {
                   SPList list = web.Lists["CountryList"];
                   SPListItem item = list.GetItemById(10);
                   SPFieldUserValue userfieldvalue = new SPFieldUserValue(web,item["ItemOwner"].ToString());
                   Console.WriteLine("Item is:" + userfieldvalue.User.Name);
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top