9

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"];
  • (Note: I've edited the question title to help future search - hope you don't mind) – Hitodama Mar 20 '12 at 12:36
  • Good question, helped me a lot +1. – JᴀʏMᴇᴇ Sep 13 '12 at 14:44
18

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.

  • 2
    Spot on, just saved my bacon. +1. – JᴀʏMᴇᴇ Sep 13 '12 at 14:45
2

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;
0

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

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.