Get OptionSet Value from Text in CRM

Posted on Updated on

public static int? GetOptionSetValueFromText(string optionSetText, OrganizationServiceContext orgContext,
string optionSetLogicalName, string entityLogicalName)
{
try
{
var request = new RetrieveAttributeRequest
{
EntityLogicalName = entityLogicalName,
LogicalName = optionSetLogicalName,
RetrieveAsIfPublished = true
};

var response = (RetrieveAttributeResponse)orgContext.Execute(request);

var optionsetMetadata = response.AttributeMetadata as PicklistAttributeMetadata;
var statusMetadata = response.AttributeMetadata as StatusAttributeMetadata;

if (optionsetMetadata != null) // optionset
{
var picklist = (PicklistAttributeMetadata)response.AttributeMetadata;

var query = from option in picklist.OptionSet.Options
where option.Label.UserLocalizedLabel.Label == optionSetText
select option.Value;
var returnValue = query.FirstOrDefault();

if (returnValue != null) return (int)returnValue;
}

if (statusMetadata != null) // status and state
{
var picklist = (StatusAttributeMetadata)response.AttributeMetadata;

var query = from option in picklist.OptionSet.Options
where option.Label.UserLocalizedLabel.Label == optionSetText
select option.Value;
var returnValue = query.FirstOrDefault();

if (returnValue != null) return (int)returnValue;
}

return null;
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(“Exception in GetOptionSetValueFromText function —” + ex.Message);
}
}

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s