Created
May 8, 2013 11:17
-
-
Save iskernel/5539817 to your computer and use it in GitHub Desktop.
TypeConverter for mapping enums to comboboxes in C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EnumToStringUsingDescription : TypeConverter | |
{ | |
public override bool CanConvertFrom(ITypeDescriptorContext context, | |
Type sourceType) | |
{ | |
return (sourceType.Equals(typeof(Enum))); | |
} | |
public override bool CanConvertTo(ITypeDescriptorContext context, | |
Type destinationType) | |
{ | |
return (destinationType.Equals(typeof(String))); | |
} | |
public override object ConvertFrom(ITypeDescriptorContext context, | |
System.Globalization.CultureInfo culture, | |
object value) | |
{ | |
return base.ConvertFrom(context, culture, value); | |
} | |
public override object ConvertTo(ITypeDescriptorContext context, | |
System.Globalization.CultureInfo culture, | |
object value, | |
Type destinationType) | |
{ | |
if (!destinationType.Equals(typeof(String))) | |
{ | |
throw new ArgumentException("Can only convert to string.", "destinationType"); | |
} | |
if (!value.GetType().BaseType.Equals(typeof(Enum))) | |
{ | |
throw new ArgumentException("Can only convert an instance of enum.", "value"); | |
} | |
string name = value.ToString(); | |
object[] attrs = | |
value.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false); | |
return (attrs.Length > 0) ? ((DescriptionAttribute)attrs[0]).Description : name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment