2

Is it possible to set a new OptionSetValue with a Dynamics CRM using only the name / label of the option?

For example, I have the following OptionSet:

1 : Male
2 : Female

If I don't have the int value, is it possible to use the string label instead? Such as...

my_optionSet = new OptionSetValue(Male)

3 Answers 3

5

We use enum to achieve it.

public enum Gender
{
    Male = 864630000,
    Female = 864630001,    
};

my_optionSet = new OptionSetValue((int)Gender.Male);

These are going to be pre-defined key:value pairs that never changes between environments. When you think about avoiding code deployments & refined to schema solution only deployments whenever new options getting added in that attribute, you can invest on Retrieve OptionSet Metadata.

4
  • 1
    This is by far the best solution Commented Jul 19, 2018 at 21:05
  • 1
    Nicely done, thanks! This still leaves the question of if I dont know the int value... outstanding, but I think I can work around this.
    – devklick
    Commented Jul 19, 2018 at 21:09
  • @ArunVinoth, Dont know how i never even considered using the service! thanks
    – devklick
    Commented Jul 19, 2018 at 21:58
  • @Klicker :) it happens for all of us Commented Jul 19, 2018 at 22:07
3

In your case I would use a Dictionary<string, int> be a mapper table then you can pass your string value then set then int parameter in OptionSetValue class.

Dictionary<string, int> mapperT = new Dictionary<string, int>();
mapperT.Add("Male", 1);
mapperT.Add("Female", 2);
my_optionSet = new OptionSetValue(mapperT["Male"]);
2

In addition to Arun answer. You can generate the Early-Bound classes and get the options set generated for you. There is a tool in the XrmToolbox for this:

enter image description here

Not the answer you're looking for? Browse other questions tagged or ask your own question.