Answered by:
Get the text value from picklists in CRM 2011 using C#

Question
-
Hello,
I am trying to read a picklist text value for a saved record in CRM 2011 and display it in a textbox on a webform. I only want to return the value that has been selected in the saved record, not all the picklist values. For example: On the Contact form i am using the Marital Status picklist and i want to retrieve the text value (married, single, etc) when the contactid is passed to a webform. Currently i am using a linq query and passing in the contactid but i am only able to get the corresponding number from the picklist, I.E. 1, 2, etc.
Thanks in advance
Duane
Tuesday, September 6, 2011 8:13 AM
Answers
-
If you're already using LINQ to query, you can use the FormattedValues collection to extract the textual representation of an OptionSetValue. E.g.:
var contacts = ( from c in xrm.ContactSet join a in xrm.AccountSet on c.ParentCustomerId.Id equals a.Id where a.Name == "Acme Pty Ltd" select new { Name = c.FullName, DOB = c.BirthDate, Gender = c.FormattedValues["gendercode"] } );
NB: you must index the collection with the Logical (all lowercase) name of the attribute.
--pogo (pat) @ pogo69.wordpress.com- Edited by pogo69 Tuesday, September 6, 2011 11:26 PM
- Marked as answer by Duane Stead Wednesday, September 7, 2011 9:07 AM
Tuesday, September 6, 2011 11:25 PM
All replies
-
.Net development isn't supported for client side operations. Only server side operations support .NET, like in plugin's and custom workflow assemblies.
Jamie Miley
Check out my about.me profile!
http://mileyja.blogspot.com
Linked-In Profile
Follow Me on Twitter!- Proposed as answer by Jamie MileyModerator Tuesday, September 6, 2011 2:43 PM
Tuesday, September 6, 2011 2:43 PMModerator -
Hi,
Using C# you can retrieve the pick list label value RetreieveAttributeRequest webservice request, you may also refer: http://nishantrana.wordpress.com/2010/12/24/get-value-for-optionset-in-crm-2011/
Jehanzeb Javeed
http://worldofdynamics.blogspot.com
Linked-In Profile |CodePlex Profile
If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".Tuesday, September 6, 2011 2:56 PM -
Hi Duane,
You need to retrieve the Microsoft.Crm.Sdk.Metadata.Option object for the picklist item you are after. This object has two properties "Label" & "Value". Value is the integer value, and label is the text.
To get this you need to do something like the following (you might need to edit a little for your environment but you'll get the gist):
string entityType = "yourEntityName"; string attributeName = "yourPicklistName"; int picklistValue = yourPicklistIntegerValue; RetrieveEntityRequest request = new RetrieveEntityRequest() { LogicalName = entityType, RetrieveAsIfPublished = true, EntityItems = EntityItems.IncludeAttributes | EntityItems.IncludeRelationships }; RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request); metadata = response.EntityMetadata; PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata; Option[] options = picklistMetadata.Options; var picklistOption = from o in options where o.Value.Value == picklistValue
select o; CrmLabel picklistLabel = ((Option)picklistOption.First()).Label;Posted "as is", with no warranties :)
Paul Dowman, CRM Developer
- Proposed as answer by Paul Dowman Tuesday, September 6, 2011 4:08 PM
- Edited by Paul Dowman Tuesday, September 6, 2011 4:09 PM Corrected typo
Tuesday, September 6, 2011 4:03 PM -
If you're already using LINQ to query, you can use the FormattedValues collection to extract the textual representation of an OptionSetValue. E.g.:
var contacts = ( from c in xrm.ContactSet join a in xrm.AccountSet on c.ParentCustomerId.Id equals a.Id where a.Name == "Acme Pty Ltd" select new { Name = c.FullName, DOB = c.BirthDate, Gender = c.FormattedValues["gendercode"] } );
NB: you must index the collection with the Logical (all lowercase) name of the attribute.
--pogo (pat) @ pogo69.wordpress.com- Edited by pogo69 Tuesday, September 6, 2011 11:26 PM
- Marked as answer by Duane Stead Wednesday, September 7, 2011 9:07 AM
Tuesday, September 6, 2011 11:25 PM -
Thanks for everybody's help on this, i went with pogo69 solution in the end.
Thanks again
Duane
Wednesday, September 7, 2011 9:08 AM -
Hello
I tried to get the Text values of PickList using both the above methods and both worked for me:
1. using Retrieve method, i created a method for this (took help of one internet link). Paste this method and call it with input parameters to get the string value of picklist.
private string GetOptionsSetTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue)
{
try
{
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true };
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata;
OptionMetadata [] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
string selectedOptionLabel = string .Empty;
foreach (OptionMetadata oMD in optionList)
{
if (oMD.Value == selectedValue)
{
selectedOptionLabel = oMD.Label.UserLocalizedLabel.Label;
break;
}
}
return selectedOptionLabel;
}
catch (System.ServiceModel.FaultException ex1)
{
string strEr = ex1.InnerException.Data.ToString();
return null;
}}
2. Using LinQ:
using System.Linq; // add this namespace
using (OrganizationServiceContext orgSvcContext = new OrganizationServiceContext (service))
{
var query1 = from c in orgSvcContext.CreateQuery<ENTITY_NAME>()
where c["crm attribute1 in lower case"].Equals("value in string")
&& c["crm attribute2 in lower case"].Equals("value in string")
&& c["crm attribute3 in lower case"].Equals("value in string")
select new
{
picklistStringValue = c.FormattedValues["picklist crm attribtue in lower case"] // formattedValues to get label string name
}
;
foreach (var q in query1)
{
string strPicklistStringValue = q.picklistStringValue.ToString();
break;
}}
thanks for the referencecs.
regards
joonFriday, October 7, 2011 8:14 AM -
Joon, I am new to CRM and C# but I believe what I need to do is the opposite of what you described above. I have an input file that I want to import into CRM. The field contains several fields that will map to Option Sets on CRM. For example, one field is the US State 2-letter abbreviation, for which I have set up an option set new_state. Since there are 50 states I wouldn't want to code for each state abbreviation.
Am I correct in my understanding that I need to find the Option set value for the state in question, before I can save this field? That is, from what I've read, it looks like I can't just take the incoming state, e.g. "AK", and assign it to the OptionSetLabel.
I tried to modify your code above as follows:
private int GetOptionsSetValueGivenText(IOrganizationService service, string entityName, string attributeName, string selectedValue) { try { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); int selectedOptionValue = 0; foreach (OptionMetadata oMD in optionList) { if (oMD.Label.UserLocalizedLabel.Label == selectedValue) { selectedOptionValue = oMD.Value.Value; break; } } return selectedOptionValue; } catch (System.ServiceModel.FaultException ex1) { string strEr = ex1.InnerException.Data.ToString(); return 0; } }
I call this function with:
int thisStateValue = GetOptionsSetTextOnValue(service, "contact", "new_state", StateAbbreviation);
But it errors with: "an object reference is required for the non-static field, method or property..."
Is my error a CRM error or a C# error? How do I correct this?
Thank you!
Monday, May 14, 2012 6:41 PM -
I used the following, which works:
public static int GetOptionSetValueGivenText(IOrganizationService service, string entityName, string attributeName, string selectedValue) { try { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); int selectedOptionValue = 0; foreach (OptionMetadata oMD in optionList) { if (oMD.Label.UserLocalizedLabel.Label == selectedValue) { selectedOptionValue = oMD.Value.Value; break; } } return selectedOptionValue; } catch (System.ServiceModel.FaultException ex1) { string strEr = ex1.InnerException.Data.ToString(); return 0; } }
Monday, May 14, 2012 9:05 PM -
There are some other nuances to using the FormattedValues as well - like whether it's a global optionset, and I've noticed a bug where it will sometimes work when first selecting the optionsetvalue and then using the formattedvalue for the same attribute... This works though:
var query1 = from c in ContactSet
where (c.Id.Equals("d9628e12-6bd3-e111-afc8-00165d00bb06"))
select new
{
AcctRole = c.AccountRoleCode,
ProviderType = c.carepro_ProviderType,
sta = c.StatusCode,
AcctRoleCode = c.FormattedValues["accountrolecode"],
AddType = c.Address1_AddressTypeCode,
AddressTypeCode = c.FormattedValues["address1_addresstypecode"],
ContId = c.Id
};
foreach (var c in query1)
{
System.Console.WriteLine("AcctRole: " + c.AcctRoleCode + " | AddressTypeCode: " + c.AddressTypeCode);
}I hope this helps. If my response answered your question, please mark the response as an answer and also vote as helpful. Michael Mayo
Monday, July 23, 2012 1:35 AM -
I don't believe that to be a bug, Michael. It is likely by design:
http://pogo69.wordpress.com/2012/03/22/crm-2011-linq-provider-formattedvalues-collection/
It makes sense for the FormattedValues collection to be populated only with values for those attributes that your query has requested. As a result, the query in my previous response above would require modification as per your discovery or the blog posting referenced here to work correctly.
--pogo (pat) @ pogo69.wordpress.com
Monday, July 23, 2012 2:11 AM -
Hi I tried a similar query with formatted values in order to retrieve the label of the statuscode so I put
l.FormattedValues["statuscode"]
but i got organizationservice fault. What am I missing?
var mylead = from l in orgContext.CreateQuery<Lead>() join u in orgContext.CreateQuery<SystemUser>() on l.OwnerId.Id equals u.Id where l.Subject == "xyz" select new { companyname = l.CompanyName, firstname= l.FirstName, lastname = l.LastName, topic = l.Subject, owner = u.FullName, //StatusReason = l.FormattedValues["statuscode"] };
- Edited by CRM elite Tuesday, July 24, 2012 3:05 AM
Tuesday, July 24, 2012 3:04 AM -
As per the discussion above; you need to explicitly request an attribute, in order for its textual equivalent to be returned via the FormattedValues collection. Try:
var mylead = from l in orgContext.CreateQuery<Lead>() join u in orgContext.CreateQuery<SystemUser>() on l.OwnerId.Id equals u.Id where l.Subject == "xyz" select new { companyname = l.CompanyName, firstname= l.FirstName, lastname = l.LastName, topic = l.Subject, owner = u.FullName, statuscode = l.StatusCode, StatusReason = l.FormattedValues["statuscode"] };
--pogo (pat) @ pogo69.wordpress.com
Tuesday, July 24, 2012 3:30 AM -
thanks pogo.Tuesday, July 24, 2012 3:10 PM