Saturday, February 11, 2012

MSCRM 2011 get optionset value (int) by its label (string) c#


This is here that I'll stop forgetting it and look for it everywhere.


internal int GetOptionsSetValueByText(Xrm.XrmServiceContext xrmService, string entityName, string attributeName, string optionSetTextValue)
    {
        RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
        {
            EntityLogicalName = entityName,
            LogicalName = attributeName,
            RetrieveAsIfPublished = true
        };
        RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)xrmService.Execut(retrieveAttributeRequest);
        if (retrieveAttributeResponse != null)
        {
            PicklistAttributeMetadata optionsetAttributeMetadata = retrieveAttributeResponse.AttributeMetadata as PicklistAttributeMetadata;
            if (optionsetAttributeMetadata != null)
            {
                OptionMetadata[] optionsetList = optionsetAttributeMetadata.OptionSet.Options.ToArray();
                foreach (OptionMetadata optionsetMetaData in optionsetList)
                {
                    if (optionsetMetaData.Label.UserLocalizedLabel.Label == optionSetTextValue)
                    {
                        return optionsetMetaData.Value.Value;
                    }
                }
            }
        }
        return -1;
    }

1 comment:

  1. Very helpful post. Thanks a lot....

    ReplyDelete