MS CRM – Get optionset value from its text

Get optionset value from its text in MS CRM

public static OptionSetValue getOptionSetValue(string entityName, string attributeName, string optionsetText)
int optionSetValue = 0;
//create query fro optiuonset
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = entityName;
retrieveAttributeRequest.LogicalName = attributeName;
retrieveAttributeRequest.RetrieveAsIfPublished = true;

//get the optionset data
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)CRMConnection._organizationService.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

//get optioset metadata
OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

//get the text of optionset by its value
foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
optionSetValue = optionMetadata.Value.Value;
return new OptionSetValue(optionSetValue);

catch (Exception ex)
//logger entry
LogMessage(System.DateTime.Now + ” — Exception: ” + ex.Message);
//LogMessage(“Exception”, entityName, attributeName, “Optionset issue: ” + ex.Message, “Exception to retrive optioset”);
return new OptionSetValue(optionSetValue);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s