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 have a field in a list that accepts an SPFieldUser object. I have an SPUser object that I would like to populate that field with, but I cannot implicitly convert from one to the other.

How would I do this conversion?

share|improve this question
    
Whenever i use this code it shows me an error such as "Nullreferenceexception was unhandled by the user code". Any Ideas? –  Prasath S Nov 26 '12 at 6:22
add comment

2 Answers

up vote 17 down vote accepted

It sounds like you've gotten two concepts slightly muddled. There are three entities that are important here:

Each row of data (List Item) has a data item for each of the fields, but fields themselves do not accept any data; they determine what the data is and how to handle it.

So in order to add an SPUser to a SPFieldUser you would have to instead add it to the relevant List Item. For example:

SPList list = SPContext.Current.List;
SPListItem listItem = list.GetItemById(1);
listItem["Author"] = SPContext.Current.Web.CurrentUser;
listItem.Update();

When the data item is set in the code above, the SPUser object is converted into a SPFieldUserValue in the background. SPFieldUserValue is just a wrapper around the SPUser class that the SPFieldUser uses to save and handle it.

Unfortunately we can't take advantage of that automatic conversion when we get the value back out, so we have to do the following:

SPList list = SPContext.Current.List;
SPListItem listItem = list.GetItemById(1);

SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, listItem["Author"].ToString());
SPUser user = userValue.User;
share|improve this answer
    
I went on to write about this and more (lookups and multiple values) in my blog, but I won't clutter this answer with more (slightly irrelevant) information: tsstsst.com/?p=44 –  Stuart Pegg Aug 17 '11 at 11:35
add comment

You can assign the SPUser object directly to the field:

SPUser user = web.SiteUsers["domain\\username"];
item["MyCustomField"] = user;
share|improve this answer
add comment

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.