Wednesday, 11 December 2013

A Quick Guide to Getting and Setting the various SPField types using C#

Introduction

This article demonstrates how to set and get the various SPField types for a SharePoint list using C#.

The examples demonstrated set and get fields from an item that belongs to a custom list. The custom list contains a number of fields, and all the fields are named based on the type of field they are. For example, there is a Text field, which has been named, textfield. This is depicted in the following picture:


Applies To

The examples demonstrated below are tested with and apply to the following versions of SharePoint:
  • SharePoint 2010
  • SharePoint 2013

Get the List, and the first SPListItem

This is the basic code for getting an item. If the list has at least one item, the first item is retrieved, otherwise a new item is created.

var web = SPContext.Current.Site.RootWeb;
var list = web.Lists.TryGetList("fieldslist");
if (list == null) return;
//Get Item 1, or add a new item if the list doesn't contain any items
SPListItem item;
item = list.ItemCount > 0 ? list.Items[0] : list.Items.Add();

Create Variables used in the Examples


//Date of current update
var t = DateTime.Now.ToLongTimeString();
//StringBuilder for output
var s = new StringBuilder();
//Variable for storing temporary values
String value;

Set and Get the Title


Set the title

//Set the Title
item["Title"] = String.Format("Title updated at {0}",t);

Get the title

value = item["Title"].ToString();
s.AppendLine(String.Format("<span>Title Field: {0}</span></br>", value));

Set and Get a Text Field

Set a text field

item["textfield"] = String.Format("At {0} dogs still can't write poems", t);
item.Update();

Get a text field

value = item["textfield"].ToString();
s.AppendLine(String.Format("<span>Text Field: {0}</span></br>", value));

Set and Get a Note (or RichText) Field

Set a note field

item["notefield"] = String.Format("At {0} dogs still can't write poems. \r\nBut then, neither can I!", t);
item.Update();

Get a note field

value = item["notefield"].ToString();
s.AppendLine(String.Format("<span>Note Field: {0}</span></br>", value));

Set and Get a Yes/No Field (Boolean)

Set a yes/no field

item["yesnofield"] = false;
item.Update();

Get a yes/no field


value = item["yesnofield"].ToString();
s.AppendLine(String.Format("<span>Yes/No Field: {0}</span></br>", value));


Set and Get a Number Field

The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display. See Double.ToString for more information.

Set a number field

item["numberfield"] = 35;
//Or
item["numberfield"] = Double.Parse("354.67");
item.Update();

Get a number field

value = item["numberfield"].ToString();
s.AppendLine(String.Format("<span>Number Field: {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F1");
s.AppendLine(String.Format("<span>Number Field (one decimal place): {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F0");
s.AppendLine(String.Format("<span>Number Field (two decimal places): {0}</span></br>", value));

Set and Get a Currency (Number) Field

A currency field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a currency. See Double.ToString for more information.

Set a currency field

item["currencyfield"] = Double.Parse("354.67");
item.Update();

Get a currency field

value = item["currencyfield"].ToString();
s.AppendLine(String.Format("<span>Currency Field: {0}</span></br>", value));
value = Double.Parse(item["currencyfield"].ToString()).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (formatted as a currency): {0}</span></br>", value));
value = (Double.Parse(item["numberfield"].ToString()) + 123).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (addition): {0}</span></br>", value));

Set and Get a Percent (Number) Field

A percentage field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a percentage. See Double.ToString for more information.

Set a percent field

item["percentfield"] = Double.Parse("0.8735");
item.Update();

Get a percent field

value = item["percentfield"].ToString();
s.AppendLine(String.Format("<span>Percent Field: {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P0");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, and as a whole number): {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P2");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, with two decimal places): {0}</span></br>", value));

Set and Get a Date Field

To set a date field, use a System.DateTime object to create a date, then assign the DateTime object to the list item's field. When you retrieve the value of a DateTime field, you can use standard date format specifiers to format the output of the value. See DateTime.ToString for more information.

Set a date field

item["datefield"] = DateTime.Now;
//Or, set the date to Now + two days
item["datefield"] = DateTime.Now.AddDays(2);
item.Update();

Get a date field

value = item["datefield"].ToString();
s.AppendLine(String.Format("<span>Date Field: {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("d");
s.AppendLine(String.Format("<span>Date Field (using the \"6/15/2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("D");
s.AppendLine(String.Format("<span>Date Field (using the \"Sunday, June 15, 2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("R");
s.AppendLine(String.Format("<span>Date Field (using the \"Sun, 15 Jun 2008 21:15:07 GMT\" format): {0}</span></br>", value));
var dateValue = DateTime.Parse(item["datefield"].ToString());
value = dateValue.AddDays(13).ToString("dd-MMM-yy");
s.AppendLine(String.Format("<span>Date Field (using a custom display format): {0}</span></br>", value));

Set and Get a Choice Field

Set a choice field

item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Green");
item.Update();
//Or, to add a new value
var choiceField = list.Fields["choicefield"] as SPFieldChoice;
if (!choiceField.Choices.Contains("Aquamarine"))
{
    choiceField.AddChoice("Aquamarine");
    choiceField.Update();
}
item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Aquamarine");
item.Update();

Get a choice field

value = item["choicefield"].ToString();
s.AppendLine(String.Format("<span>Choice Field: {0}</span></br>", value));

Set and Get a Multi-Choice Field

Set a multi-choice field

var choicevalues = new SPFieldMultiChoiceValue();
choicevalues.Add("Green");
choicevalues.Add("Blue");
item["multiplechoicefield"] = choicevalues;
item.Update();

Get a multi-choice field

list.Fields["multiplechoicefield"].ParseAndSetValue(item, choicevalues.ToString());
var multipleChoiceValues = new SPFieldMultiChoiceValue(item["multiplechoicefield"].ToString());
s.AppendLine(String.Format("<span>Multiple Choice Field: {0}</span></br>", multipleChoiceValues));
for (int i = 0; i <= multipleChoiceValues.Count - 1; i++)
{
    s.AppendLine(String.Format("<span>Multiple Choice Field, value {0}: {1}</span></br>", i, multipleChoiceValues[i]));
}

Set and Get a Person Field

Set a person field

item["personfield"] = web.EnsureUser("contoso\\fred");
//or
item["personfield"] = web.EnsureUser("fred@contoso.com");
item.Update();

Get a person field

value = item["personfield"].ToString();
s.AppendLine(String.Format("<span>Person Field: {0}</span></br>", value));
var userFieldValue = new SPFieldUserValue(web, item["personfield"].ToString());
s.AppendLine(String.Format("<span>Person Field: Name = {0}, Email = {1}</span></br>", userFieldValue.User.Name, userFieldValue.User.Email));

Set and Get a Multi-Person Field

Set a multi-person field

var lotsofpeople = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
var personA = web.EnsureUser("contoso\\fred");
var personAValue = new SPFieldUserValue(web, personA.ID, personA.LoginName);
var personB = web.EnsureUser("contoso\\barnie");
var personBValue = new SPFieldUserValue(web, personB.ID, personB.LoginName);
lotsofpeople.Add(personAValue);
lotsofpeople.Add(personBValue);
item["lotsofpeoplefield"] = lotsofpeople;
item.Update();

Get a multi-person field

var fieldUserValueCollection = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
s.AppendLine(String.Format("<span>MultiPerson Field: {0}</span></br>", fieldUserValueCollection));
var userCount = 1;
foreach (SPFieldUserValue v in fieldUserValueCollection)
{
    s.AppendLine(String.Format("<span>MultiPerson Field, value {0}: {1}</span></br>", userCount, v.User.Name));
    userCount++;
}

Set and Get a Lookup Field

Set a lookup field

var lookupField = list.Fields["lookupfield"] as SPFieldLookup;
var lookupList = web.Lists[new Guid(lookupField.LookupList)];
var lookupitem = lookupList.Items[0];
//-or-
//lookupitem = lookupList.GetItemByUniqueId(new Guid("fc71b84c-74d4-4f7c-9eed-fb7a5fbe24a6"));
//-or-
//lookupitem = lookupList.GetItemById(1);
var lookupValue = new SPFieldLookupValue(lookupitem.ID, lookupitem.ID.ToString());
item["lookupfield"] = lookupValue;
item.Update();

Get a lookup field

var lookupItemValue = new SPFieldLookupValue(item["lookupfield"].ToString());
value = lookupItemValue.LookupValue;
s.AppendLine(String.Format("<span>Lookup Field: {0}</span></br>", value));

Setting and Getting a HyperLink Field

Set a hyperlink field

var hyperlinkField = list.Fields["hyperlinkfield"] as SPFieldUrl;
var urlFieldValue = new SPFieldUrlValue();
urlFieldValue.Description = "Microsoft";
urlFieldValue.Url = "http://www.microsoft.com";
//SharePoint 2013 Only
hyperlinkField.ValidateParseAndSetValue(item, urlFieldValue.ToString());
//SharePoint 2010 and SharePoint 2013
hyperlinkField.ParseAndSetValue(item, urlFieldValue.ToString());
item.Update();

Get a hyperlink field

var hyperlinkFieldValue = new SPFieldUrlValue(item["hyperlinkfield"].ToString());
value = String.Format("<a href=\"{1}\" alt=\"{0}\">{0}</a>", hyperlinkFieldValue.Description, hyperlinkFieldValue.Url);
s.AppendLine(String.Format("<span>Hyperlink Field: {0}</span></br>", value));

Setting and Getting a Managed Metadata Field

Set a Managed Metadata field

var managedMetaDataField = list.Fields["managedmetadatafield"] as TaxonomyField;
var termsetId = managedMetaDataField.TermSetId;
var termstoreId = managedMetaDataField.SspId;
var taxonomySession = new TaxonomySession(web.Site);
var termstore = taxonomySession.TermStores[termstoreId];
var termset = termstore.GetTermSet(termsetId);
var termname = "Rubbish Tip";
var terms = termset.GetTerms(termname, false);
Term term;
if (terms.Count == 0)
{
    term = termset.CreateTerm(termname, termstore.Languages[0]);
    termstore.CommitAll();
}
else
{
    term = terms[0];
}
managedMetaDataField.SetFieldValue(item, term);
item.Update();

Get a Managed Metadata field

var taxonomyFieldValue = item["managedmetadatafield"] as TaxonomyFieldValue;
s.AppendLine(String.Format("<span>Taxonomy Field: {0} ({1})</span></br>", taxonomyFieldValue.Label, taxonomyFieldValue.TermGuid));

Setting and Getting a Multiple Valued Managed Metadata Field

Set a Multiple Valued Managed Metadata field

var managedMetaDataField = list.Fields["managedmetadatafield"] as TaxonomyField;
var termsetId = managedMetaDataField.TermSetId;
var termstoreId = managedMetaDataField.SspId;
var taxonomySession = new TaxonomySession(web.Site);
var termstore = taxonomySession.TermStores[termstoreId];
var termset = termstore.GetTermSet(termsetId);
var multipleManagedMetaDataField = list.Fields["multiplemanagedmetadatafield"] as TaxonomyField;
var termCollection = new TaxonomyFieldValueCollection(multipleManagedMetaDataField);
var taxonomyLabels = new[] {"Frog Catcher", "Giraffe Stealer", "Moon Dog"};
Term term;
foreach (var label in taxonomyLabels)
{
    var terms = termset.GetTerms(label, false);
    term = null;
    if (terms.Count == 0)
    {
        term = termset.CreateTerm(label, termstore.Languages[0]);
        termstore.CommitAll();
    }
    else
    {
        term = terms[0];
    }
    var termValue = new TaxonomyFieldValue(multipleManagedMetaDataField);
    termValue.TermGuid = term.Id.ToString();
    termValue.Label = term.Name;
    termCollection.Add(termValue);
}
multipleManagedMetaDataField.SetFieldValue(item, termCollection);
item.Update();

Get a Multiple Valued Managed Metadata field

var taxonomyFieldValueCollection = item["multiplemanagedmetadatafield"] as TaxonomyFieldValueCollection;
value = String.Empty;
foreach (var taxonomyValue in taxonomyFieldValueCollection)
{
    value = String.IsNullOrEmpty(value)
                ? String.Format("{0} ({1})", taxonomyValue.Label, taxonomyValue.TermGuid)
                : String.Format("{0}, {1} ({2})", value, taxonomyValue.Label, taxonomyValue.TermGuid);
    //Or, to use get the term
    var currentTerm = termstore.GetTerm(new Guid(taxonomyValue.TermGuid));
    //do something with the term
}
s.AppendLine(String.Format("<span>Multiple Taxonomy Field Values: {0})</span></br>", value));

Setting and Getting a Calculated Field

Calculated fields work in a different manner to that of normal fields. A formula is set on the list field, and when a list item is added or updated, the value of the column for that list item is calculated based on the formula.

Get a Calculated Field value
Get a reference to the calculated field. Then get a reference to the list item. Finally, call the GetFieldValueAsText method, passing in the value of the item objects calculated field.

var calculatedfield = list.Fields["calculatedfield"] as SPFieldCalculated;
value = calculatedfield.GetFieldValueAsText(item["calculatedfield"]);
s.AppendLine(String.Format("<span>Calculated Field: {0}</span></br>", value));

Set the Properties of a Calculated Field
The value of a calculated field is calculated at the time a list item is created or updated. It is not possible to directly set this value. You can use the following methods to set the formula though, which is used to calculate the fields value. Before looking at these methods, there are four main properties that can be set on a calculated field; Formula, OutputType, DisplayFormat and DateFormat. Which properties you need to set, depends on the value of the calculation.
  1. Formula: The formula used to calculate the value. 
  2. OutputType: The type of the value that results from the calculation. Supported types are, Text, Number, Integer, Currency, Boolean and DateTime. 
  3. DisplayFormat: Used with number, integer and currency to specify the number of decimal places
  4. DateFormat: Used with DateTime to specify Date, or Date and Time.
In the following example, we perform the following tasks:
  1. View the current formula
  2. View the current display format
  3. Change the display format from two decimal places to four decimal places
  4. Change the output type from currency to integer
  5. Change the formula, output type and set the date format

//Configuring the calculated field
s.AppendLine(String.Format("<span>Calculated Field Formula: {0}</span></br>", calculatedfield.Formula));
s.AppendLine(String.Format("<span>Calculated Display Format: {0}</span></br>", calculatedfield.DisplayFormat));
s.AppendLine(String.Format("<span>Calculated Output Type: {0}</span></br>", calculatedfield.OutputType));
calculatedfield.DisplayFormat = SPNumberFormatTypes.FourDecimals;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Display Format 4 decimals): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.OutputType = SPFieldType.Integer;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Output Type Integer): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.Formula = "=[datefield]+90";
calculatedfield.DateFormat = SPDateTimeFieldFormatType.DateOnly;
calculatedfield.OutputType = SPFieldType.DateTime;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Updated Formula, Date Format and Output Type): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));


See Also