Aug 21, 2013

Retrieving OptionSet Label using Value and Wise versa

Just though of posting a code snippet. This c# code could be helpful for someone. Code written as a static methods.

Pass the Value and retrive the Label.

public static string GetOptionsetLabel(IOrganizationService _service, String _entityName, String _attribute, int _optionVal)
    {
        string _optionName = String.Empty;

        RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
        {
            EntityLogicalName = _entityName,
            LogicalName = _attribute,
            RetrieveAsIfPublished = true
        };

        RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
        AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
        PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata;
        
        foreach (OptionMetadata optionMeta in picklistMetadata.OptionSet.Options)
        {
            if (optionMeta.Value == _optionVal)
            {
                _optionName = optionMeta.Label.UserLocalizedLabel.Label;
                break;
            }
        }
        return _optionName;
    }

Now pass the Label and retriev the Value;

public static int GetOptionSetVal(IOrganizationService _service, String _entityName, String _attribute, String _optionLabel)
    {
        int _optionVal = -1;

        RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
        {
            EntityLogicalName = _entityName,
            LogicalName = _attribute,
            RetrieveAsIfPublished = true
        };

        RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
        AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
        PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata;
        
        foreach (OptionMetadata optionMeta in picklistMetadata.OptionSet.Options)
        {
            if (optionMeta.Label.UserLocalizedLabel.Label == _optionLabel)
            {
                _optionVal = optionMeta.Value.Value;
                break;
            }
        }
        return _optionVal;
    }

Cheers.