Tuesday, October 18, 2011

CRM 2011 Get OptionSetValue Label Text

In CRM 2011, when you try to get the value of an OptionSet, you will always get an Integer value instead of the label value.

Below is the Helper method which is used to retrieve the label of the selected option set

public static string GetOptionSetValueLabel(IOrganizationService service, Entity entity, string attribute, OptionSetValue option)
{
string optionLabel = String.Empty;

RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = entity.LogicalName,
LogicalName = attribute,
RetrieveAsIfPublished = true
};

RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata;

// For every status code value within all of our status codes values
// (all of the values in the drop down list)
foreach (OptionMetadata optionMeta in
picklistMetadata.OptionSet.Options)
{
// Check to see if our current value matches
if (optionMeta.Value == option.Value)
{
// If our numeric value matches, set the string to our status code
// label
optionLabel = optionMeta.Label.UserLocalizedLabel.Label;
}
}

return optionLabel;
}