Introduction
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 and also while setting the optionset, an integer value is required.
Using the code
Below is the helper code to fetch OptionSet
text or value depending on the requirement.
static CRMHelper
{
public static int getOptionSetValue(string entityName, string attributeName, string optionsetText)
{
int optionSetValue = 0;
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = entityName;
retrieveAttributeRequest.LogicalName = attributeName;
retrieveAttributeRequest.RetrieveAsIfPublished = true;
RetrieveAttributeResponse retrieveAttributeResponse =
(RetrieveAttributeResponse)OrganizationService.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata picklistAttributeMetadata =
(PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;
foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
{
if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
{
optionSetValue = optionMetadata.Value.Value;
return optionSetValue;
}
}
return optionSetValue;
}
public static string getOptionSetText(string entityName, string attributeName, int optionsetValue)
{
string optionsetText = string.Empty;
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = entityName;
retrieveAttributeRequest.LogicalName = attributeName;
retrieveAttributeRequest.RetrieveAsIfPublished = true;
RetrieveAttributeResponse retrieveAttributeResponse =
(RetrieveAttributeResponse)OrganizationService.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata picklistAttributeMetadata =
(PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;
foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
{
if (optionMetadata.Value == optionsetValue)
{
optionsetText = optionMetadata.Label.UserLocalizedLabel.Label;
return optionsetText;
}
}
return optionsetText;
}
}