I had to set an OptionSetValue in a plugin this week and for some reason I totally forgot how to do it, which kept causing my plugin to crash.
Like all things in CRM, once you have done it you wonder what all the fuss was about and how simple it seems but before you have cracked it, it can be very frustrating.
The other unusual thing I found was I couldn’t Google any examples, so I thought I would show an example on this blog so if I can’t do it in the future at least I would know where to look.
I will briskly take you through the basics. OptionSetValue is a drop down list in CRM. The OptionSetValue is a list of int values linked with a metadata list of text values. I think it is done like this so you can store the OptionSets in a database and you have to split them up.
If you want to find the text value you have to lookup the value in the metadata, I have blogged about that before, go here if you want to know how to look up the metadata value of an optionSet
The main thing which was confusing me is firstly OptionSetValue is a class and to then get the actual OptionSetValue you have to put you class name and then Value. For some reason I was then trying to set just the value, which is stupid when I think about it but it was late on a Friday and my brain had clearly stopped working for the week.
OptionSetValue is a class and it has two constructors, click here for the api
Now you can see that one of the constructors takes an int32 value. Most of the time if you are creating an OptionSetValue which you want to write to a CRM object then you will pass in the int value of the optionset. This is a common Gotcha, people will often set this value to a value which isn’t in the OptionSet values in CRM. To find the values, you need to open the entity going through solutions (basically as if you are going to edit it) with the optionset you want the values for.
Selected the optionSet in the fields, open the optionSet until you have a list of the Options. When you select one of the options you will see on the right it shows you the optionset Label and below that is the value (which is an int)
So from the above you can see the int number you want to assign to the optionSetValue is 143570000.
so to create and set an OptionSetValue you would do this
OptionSetValue op = new OptionSetValue(143570000);
shortlist.new_StatusSelectedCheckbox = op;
In the example shortlist is an entity object and new_StatusSelectedCheckbox is the field. To get the value from an optionSetValue you would do this
the number below is the value.
As I have said before one of the most common problems people will experience is they will try and set an OptionSetValue to an int number not in the list of dropdown values.
The OptionSetValue class api is here but it really only has the Value method to set and get int value of the OptionSetValue class