Friday, 15 November 2013

Get Option set values in CRM 2011 using C#.

string optionSetText="Advertisement"
OptionSetValue leadSource = new OptionSetValue(getOptionSetValue(lead.LogicalName, "fieldAttribute", optionSetText));
newLead["leadsourcecode"] = leadSource;

public int getOptionSetValue(string logicalName, string attributeName, string optionsetText)
        {
            int optionSetValue=0;
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
            retrieveAttributeRequest.EntityLogicalName = "lead";
            retrieveAttributeRequest.LogicalName = attributeName;
            retrieveAttributeRequest.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

            OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

            foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
            {
                if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
                {
                    optionSetValue = optionMetadata.Value.Value;
                    return optionSetValue;
                }

            }
            return optionSetValue;
        }

No comments:

Post a Comment