Entity fields that have an OptionSet data type contains an integer value and a string label.
You will mostly use the integer value when you use the field value in your code, no matter if you use the standard late bound method, for instance in your CRM plugins:
account["statecode"] = new OptionSetValue(0); //0 = Active
… or if you use early binding and XRM entities:
Account a;
a.StateCode = AccountState.Active;
In the last example, you will of course see the label, and you can assign it using the generated enums. But in some cases, you may want to get the label text as a string. Here are a couple of methods that may help you do just that:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace CRM_Developers_How_To
{
public class CrmHelper
{
/// <summary>
/// Retrieve the OptionSet label for the LCID of the account the IOrganizationService is using
/// </summary>
/// <param name="entityName">The name of the enitity with the OptionSet parameter</param>
/// <param name="fieldName">The name of the OptionSet field</param>
/// <param name="optionSetValue">The integer value of the OptionSet field</param>
/// <param name="service">An IOrganizationService instance connected to the CRM</param>
/// <returns>The OptionSet label</returns>
public static string GetOptionSetValueLabel(string entityName, string fieldName, int optionSetValue, IOrganizationService service)
{
var attReq = new RetrieveAttributeRequest();
attReq.EntityLogicalName = entityName;
attReq.LogicalName = fieldName;
attReq.RetrieveAsIfPublished = true;
var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;
return attMetadata.OptionSet.Options.Where(x => x.Value == optionSetValue).FirstOrDefault().Label.UserLocalizedLabel.Label;
}
/// <summary>
/// Retrieve the OptionSet label for a specified LCID
/// </summary>
/// <param name="entityName">The name of the enitity with the OptionSet parameter</param>
/// <param name="fieldName">The name of the OptionSet field</param>
/// <param name="optionSetValue">The integer value of the OptionSet field</param>
/// <param name="lcid">The language code id</param>
/// <param name="service">An IOrganizationService instance connected to the CRM</param>
/// <returns>The OptionSet label</returns>
public static string GetOptionSetValueLabel(string entityName, string fieldName, int optionSetValue, int lcid, IOrganizationService service)
{
var attReq = new RetrieveAttributeRequest();
attReq.EntityLogicalName = entityName;
attReq.LogicalName = fieldName;
attReq.RetrieveAsIfPublished = true;
var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;
return attMetadata.OptionSet.Options.Where(x => x.Value == optionSetValue).FirstOrDefault().Label.LocalizedLabels.Where(l => l.LanguageCode == lcid).FirstOrDefault().Label;
}
}
}