Friday, 19 May 2017

MSCRM - Retrieve optionset label - RetrieveAttributeRequest - optionsetmetada - C#


Hello All,

Below is a quick code snippet that can retrieve picklist label based on value,

private string GetOptionsSetTextOnValue(IOrganizationService service,string entityName, string attributeName, int option)  
     {  
       RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest  
       {  
         EntityLogicalName = entityName,  
         LogicalName = attributeName,  
         RetrieveAsIfPublished = true  
       };  
       RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);  
       PicklistAttributeMetadata attributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse?.AttributeMetadata;  
       if (attributeMetadata == null) return string.Empty;  
       var currentOption = attributeMetadata?.OptionSet?.Options?.FirstOrDefault(x => x.Value == option);        
       return currentOption?.Label?.UserLocalizedLabel?.Label != null ? currentOption.Label.UserLocalizedLabel.Label : string.Empty;  
     }  

To know more on conditional operator  with question mark, please refer
http://exptechsolutions.blogspot.com/2017/05/c-null-conditional-operator-null-check.html

Null conditional operators are the question marks in the above c# code which is a cool functionality that helps to avoid clumsy if conditions.

1 comment:

  1. Greate! Amazing solutions, this information is really helpful for Microsoft CRM developer. Thank you so much for sharing this with us!

    ReplyDelete