Get the string value from OptionSetValue in CRM Plugin

Mr Lahey picture Mr Lahey · Jul 21, 2014 · Viewed 26.5k times · Source

I'm wondering how to get the string value of an OptionSet in a CRM plugin I am making. I thought all I had to do was pass the int value to OptionSetValue, but that doesn't seem to be working. Here is my code:

aBillingFrequencyCode = new OptionSetValue(myContract.BillingFrequencyCode.Value).ToString();

But the output is just

Microsoft.Xrm.Sdk.OptionSetValue

Any ideas?

Answer

Nicknow picture Nicknow · Jul 22, 2014

You can retrieve OptionSet labels without retrieving all of the entity's metadata. I've provided two methods. One will use the language code (LCID) of the account that IOrganizationService is running under. The other allows you to specify the LCID.

Note, if you are going to use these extensively in code you may want to consider caching the value to improve performance - this will depend on your specific applications requirements.

If you plan to retrieve these values for multiple Option Sets on a single entity at the same time you should use Guido's code above and retrieve all the entity metadata in one call to reduce the number of calls you are required to make to CRM. Hence, each of our code snippets is more efficient in certain circumstances.

//This method will return the label for the LCID of the account the IOrganizationService is using
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;
}

//This method will return the label for the specified LCID
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;
}