CRM 2011 Get OptionSetValue Value through Label
Sometimes we want to be able to get the OptionSetValue value from the label itself. One way is to use the metadata request and loop through it but this is a cumbersome way.
The easier way is to put those OptionSetValue data into an enum like this:
We use Description Attribute for the Label so that it supports string format.
Then we use this helper method:
And there you go. You can easily get the value like this:
Hope this helps,
Andreas
The easier way is to put those OptionSetValue data into an enum like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public enum Approach { [Description( "Value Marketing" )] ValueMarketing = 100000000, [Description( "Communications & Events" )] CommEvents = 100000001, [Description( "Investigate" )] Investigate = 100000002, [Description( "Key Account Management" )] KeyAccManagement = 100000003, [Description( "Pro-Active Price & Product" )] ProActivePriceProduct = 100000004 } |
We use Description Attribute for the Label so that it supports string format.
Then we use this helper method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public static class EnumHelper { public static T GetValueFromDescription<t>( string description) { var type = typeof (T); if (!type.IsEnum) throw new InvalidOperationException(); foreach (var field in type.GetFields()) { var attribute = Attribute.GetCustomAttribute(field, typeof (DescriptionAttribute)) as DescriptionAttribute; if (attribute != null ) { if (attribute.Description == description) return (T)field.GetValue( null ); } else { if (field.Name == description) return (T)field.GetValue( null ); } } throw new ArgumentException( "Not found." , "description" ); } } |
And there you go. You can easily get the value like this:
1 2 3 | new_entity entity = new new_entity(); entity.new_approach = new OptionSetValue(( int )EnumHelper.GetValueFromDescription<OptionSet.Approach>( "Value Marketing" )); |
Hope this helps,
Andreas
Great post! I also use the metadata request to get OptionSetValue value.
ReplyDelete