Question

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?

Was it helpful?

Solution

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;

OTHER TIPS

You can assign the SPUser object directly to the field:

SPUser user = web.SiteUsers["domain\\username"];
item["MyCustomField"] = user;

Gets the user that is associated with the field value.

SPFieldUserValue userValue=someValue;
SPUser user = userValue.User;
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top