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 .
Can you show to how add an item where you need to populate the lookup field from another object?
ReplyDeleteI have List A and a look up column in List B.
So I need to add an item to list A and the lookup value in list B
You need to create a new FieldLookupValue and then pass the appropriate values of Lookup List item.
ReplyDeleteLooks like code is missing for "Manipulate Lookup Field Value - Set Field Value". It's the same as for Get Field Value.
ReplyDeleteThanks Alex for pointing this out. I've update the post.
ReplyDeleteAwesome tip, I was hoping that I could set LookupText on the LookupField but instead I have to read the listitem id via COM to complete the LookupFieldValue.
ReplyDelete