Show MS CRM Optionset values in Dropdownlist in Asp.net

Sometime customers have requirement to create MS CRM records through custom asp.net pages, and if we have optionset in our entity we might want to display optionset valeus in dropdownlist in our Web page. We can use following code to populate optionset values in dropdownlist.

public Dictionary<int, string> RetrieveOptionsetMetadata(IOrganizationService _iOgranizationService)

{ //Dictionary to store value and text

Dictionary<int,string> _DropdownDatasource=newDictionary<int,string>();

//Create request to fetch optionset

RetrieveAttributeRequest _Request = new RetrieveAttributeRequest{

EntityLogicalName =“EntityName”, //Change entity name here

LogicalName =“OptionsetFieldName”, //Change field name here

RetrieveAsIfPublished =true

};

// Execute the request

RetrieveAttributeResponse _Response =(RetrieveAttributeResponse)_iOgranizationService.Execute(_Request);

PicklistAttributeMetadata _PicklistAttributeMetadata = (PicklistAttributeMetadata)_Response.AttributeMetadata;

OptionMetadata[] optionList =_PicklistAttributeMetadata.OptionSet.Options.ToArray();

foreach (OptionMetadata _Optionset in optionList) {

_DropdownDatasource.Add(int.Parse(_Optionset.Value.ToString()), _Optionset.Label.UserLocalizedLabel.Label);

}

return _DropdownDatasource;

}

After that we can set datasource for dropdownlist like below

DropDownList1.DataSource = RetrieveOptionsetMetadata(_iOgranizationService);

DropDownList1.DataBind();

Enjoy !!!

Leave a Reply

Your email address will not be published. Required fields are marked *