Get and Set User Field SharePoint C#

Get and Set SharePoint Field using C#

In this post, I will explain How to programmatically Get and Set a SharePoint User Field value using C#?


Get User Field Value SharePoint C#

Consider, you have a SharePoint List called “Users” that has a person and group field and you would like to get and read SharePoint User Field Value programmatically using C#.

Get and Set User Field SharePoint C#

In this case, you should use the below code with your List name and field name to get person field value using C#

Code

public string GetUserFieldValue() {
 using(SPSite site = new SPSite(SPContext.Current.Site.Url)) {
  using(SPWeb web = site.OpenWeb()) {
   SPList list = web.Lists["Users"];
   SPListItem item = list.GetItemById(1);
   string currentValue = item["FieldName"].ToString();
   SPFieldUser userField = list.Fields.GetFieldByInternalName("FieldName");
   SPFieldUserValue itemValue = (SPFieldUserValue)userField.GetFieldValue(currentValue);
   SPUser user = itemValue.User;
   Return user.Name;
  }
 }
}

Set User Field SharePoint C#

Again, You are using the same list “Users” and you would like to update and set SharePoint User Field Value programmatically using C#.

In this case, you should use the below code with your List name and field name to set person field value using C#

Code

public void SetUserFieldValue() {
 using(SPSite site = new SPSite(SPContext.Current.Site.Url)) {
  using(SPWeb web = site.OpenWeb()) {
   SPList list = web.Lists["Users"];
   SPListItem item = list.GetItemById(1);
   web.EnsureUser(@"domain\username");
   SPUser user = web.AllUsers[@"domain\username"];
   item["FieldName"] = user;
   item.Update();
  }
 }
}

Note: the Field Class: SPFieldUser, and Field Value Class: SPFieldUserValue.


Conclusion

In conclusion, we have learned how to Get and Set a SharePoint User Field value using Server Object Model C#?

Applies To

  • SharePoint 2016.
  • SharePoint 2013.
  • SharePoint 2010.
  • C# SSOM.
You may also like to read
Have a Question?

If you have any related questions, please don’t hesitate to ask it at deBUG.to Community.

Leave a Reply

Scroll to Top