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?
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It only takes a minute to sign up.Sign up to join this community
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.
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;