In the post How do I have an enum bound combobox with custom string formatting for enum values? and How to set space on Enum shows how to add descriptions to Enum values to be able to add spaces which is usable when binding comboboxes to string values. My case is that the selected item of this combobox is also bound to another control. using the solutions i have found with that link, the value of the selected item that I am getting is still the value of the Enum without the spaces.
My Enum goes something like below
[TypeConverter(typeof(EnumToStringUsingDescription))]
public enum SCSRequestType {
[Description ("Change Request")]
ChangeRequest = 4,
[Description("Documentation")]
Documentation = 9,....
}
And also I am using the below typeconverter.
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;
}
}
Am I missing something here, how can i force the combobox's selected item to be the value of the descriptions of the Enum values. I am also open for alternatives.