After my few posts on Client Object Model, I had come to questions on how to manipulate choice and lookup field. I’ve tried to explain a bit on how you can manipulate these field values with Client Object Model.
Manipulate Choice Field Value (Single Choice)
You can manipulate the single choice field value as like string. For example, let’s consider a field, ProductStatus in Product list. The field values might be “In Stock, Out of Stock, Invalid” as shown below:
Figure 1: Single Choice Field (ProductStatus) in product list.
To access the value of the field using Client Object Model, you can use code shown below:
- Get Field value: You can just get the field value as string
var productStatus = productItem["ProductStatus"].ToString();
- Set Field value: You can use any of the following statement to set the field value
productItem["ProductStatus"] = "In Stock";
productItem["ProductStatus"] = "Out of Stock";
productItem["ProductStatus"] = "Invalid";
Manipulate Choice Field Value (Multiple Choice)
If the choice field support multiple values then you need to use string array to manipulate field values. For example, consider there’s a field ‘product types’ in product list whose values can be Foods, electronics, Cars etc. Also consider the field values can be multiple, that’s mean a product types can be more than one type. The following figure shows the field
Figure 2: Multiple Choice Field
In that case you need string array to access the multiple choice field value as shown as shown below:
- Get Field Value:
var productTypes = (string[]) (productItem["ProductType"]);
- Set Field Value:
productItem["ProductType"] = new string[] { "Furniture", "Toys" };
Manipulate Lookup Field Value
To manipulate lookup field you need to use the code as shown below:
- Get Field Value:
var lookupFieldValue = (productItem["FieldName"] as FieldLookupValue);
- Set Field Value
//100 here is the lookup field id value
productItem["FieldName"] = new FieldLookupValue(){LookupId = 100};
The FieldLookupValue is part of SharePoint Client OM .