Wednesday, 16 November 2016

Get the option set values of a field in an entity in Dynamics CRM using SDK and C# code

Hi,

Today we got a requirement to retrieve OptionSet values of a field from an entity in CRM. Here is the sample code of it.

public static OptionSetMetadata GetOptionSetsValuesInAnEntity(string entityName, string attributeName, IOrganizationService service)
{
       string AttributeName = attributeName;
       string EntityLogicalName = entityName;
       RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
       {
             EntityFilters = EntityFilters.All,
             LogicalName = EntityLogicalName
       };
       RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
       Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
       Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
       Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
      // Use below code to get the Option Set Item Name from Value (optionSetValue)
      //IList<Microsoft.Xrm.Sdk.Metadata.OptionMetadata> OptionsList = (from o in options.Options
      //                                     where o.Value.Value == optionSetValue
      //                                     select o).ToList();
      // string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
      return options;
}

Hope this helps.

--
Happy CRM'ing

Gopinath

No comments:

Post a Comment