Thursday, August 25, 2011

Get string value of OptionSet in CRM 2011

If you need to retrieve StateCode or StatusCode or other OptionSet of attribute, then simply use code bellow:


public static OptionMetadataCollection GetOptionsSetByAttribute(IOrganizationService service, string entityName, string attributeName)
{

var retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = entityName;
retrieveAttributeRequest.LogicalName = attributeName;
retrieveAttributeRequest.RetrieveAsIfPublished = true;

var retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);

var optionMetadataCollection = (((StatusAttributeMetadata) retrieveAttributeResponse.AttributeMetadata).OptionSet).Options;

//foreach (OptionMetadata optionMetadata in optionMetadataCollection)
//{
// Here you can add your advanced logic.....
// optionMetadata.Label.UserLocalizedLabel.Label = "Teset";
//}
// or simply return OptionMetadataCollection....
return optionMetadataCollection;

}

To use it just write:
OptionMetadataCollection metadatas = GetOptionsSetByAttribute(this.OrganizationService, "new_cars", "statuscode");   

3 comments:

  1. Tip: Instead of casting to StatusAttributeMetadata, cast to its base class EnumAttributeMetadata.

    Kind regards,
    Daniel

    ReplyDelete
  2. its showing me an error
    that "this" is not valid

    ReplyDelete