Thursday, July 10, 2014

Get Optionset value from text

Here you go with the code


Code:
public static int GetOptionSetValueGivenText(IOrganizationService service, string entityName, string attributeName, string selectedValue)
        {
            try
            {
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true };
                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                int selectedOptionValue = 0;
                foreach (OptionMetadata oMD in optionList)
                {
                    if (oMD.Label.UserLocalizedLabel.Label == selectedValue)
                    {
                        selectedOptionValue = oMD.Value.Value;
                        break;
                    }
                }
                return selectedOptionValue;
            }
            catch (System.ServiceModelFaultException ex1)
            {
                string strEr = ex1.InnerException.Data.ToString();
                return 0;
            }

        }

No comments: