Convert Comma Separated String Values to Multi-Select Option Set in C# Dynamics 365

In Dynamics 365 CRM Web API you receive multiple input values for a Multi-Select Option type attribute. We generally accept those values in comma or semicolon separated string. But we cannot assign this string directly to the attribute which type is Multi-Select Option Set.

In this article we will see how to covert those multiple values in string to Multi-Select Option Sets.

For Multi-Select Option Sets attribute you need to use OptionSetValueCollection class in C#.

To test below code. Create C# console app (.net framework version 4.6.1 or greater) and in the app add Microsoft.Xrm.Sdk dll version 9.0 or greater.

‎
using System;
using Microsoft.Xrm.Sdk;

namespace MyConsoleApp
{
    public enum Color
    {
        Red = 100,
        Yellow = 101,
        Blue = 102,
        Green = 103
    }
    internal class Program
    {
        private static OptionSetValueCollection SetMutiOptionSetValue(string values)
        {
            char[] delimeters = { ',' };

            string[] options = values.Split(delimeters, StringSplitOptions.RemoveEmptyEntries);

            OptionSetValueCollection optionSetValues = new OptionSetValueCollection();

            if (options.Length > 0)
            {
                foreach (string c in options)
                {
                    optionSetValues.Add(new OptionSetValue(int.Parse(c)));
                }
            }
            return optionSetValues;
        }
        static void Main(string[] args)
        {
            string colors = "102,103,101";
            try
            {
                OptionSetValueCollection selectedColors = SetMutiOptionSetValue(colors);

                foreach (OptionSetValue color in selectedColors)
                {
                    Console.WriteLine(Enum.GetName(typeof(Color), color.Value));
                }
            }
            catch (Exception ex)
            { 
               Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}
‎

For Multiselect option value generally you get an

integer values associate with the name. Using those, you have to set options values for Multiselect option attribute. Above code is just an example of how we can convert string values in the Multiselect option set using OptionSetValueCollection.

In Dynamics 365 for Multiselect option attribute you can directly assign returned (from SetMutiOptionSetValue method above)OptionSetValueCollection (While updating/creating records through API or plugin) it will set all the values for that attribute.

You can reuse SetMutiOptionSetValue for any Multiselect option attribute in Dynamics 365. Change delimiter value as per your requirements.


Subscribe Now!

Subscribe Us For Latest Articles