Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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

Thanks a lot!

share|improve this question
    
(Note: I've edited the question title to help future search - hope you don't mind) –  SPArchaeologist Mar 20 '12 at 12:36
    
Thanks, your title suits much better! –  MOI Mar 21 '12 at 9:25
    
Good question, helped me a lot +1. –  DeeMac Sep 13 '12 at 14:44

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer
2  
Spot on, just saved my bacon. +1. –  DeeMac Sep 13 '12 at 14:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.