C# Mapping Enums To Comboboxes with Style

I was working on my bachelor degree project (a code generator for Atmega16) these days and found myself having a nasty enum/combobox problem.

I usually map a enum directly to the data source of a combobox. Unfortunately for the enum below, it didn't look the way I wanted:

public enum WdtOscillatorCycles
{
_16k = 0x00,
_32k,
_64k,
_128k,
_256k,
_512k,
_1024k,
_2048k
}

Ugly mapping
I wouldn't want for the user to see the leading underscore. Furthermore, I wanted to find a solution in which I could display instead of _16k something like 16000 Cycles without complicating myself too much.

I did some research and I found a solution here. Stated briefly, you need to derive a class from TypeConverter (see the implementation I found here) and start writing your enums like this:

[TypeConverter(typeof(EnumToStringUsingDescription))]
public enum WdtOscillatorCyclesImproved
{
[Description("16000 Cycles")]
_16k = 0x00,
[Description("32000 Cycles")]
_32k,
[Description("64000 Cycles")]
_64k,
[Description("128000 Cycles")]
_128k,
[Description("256000 Cycles")]
_256k,
[Description("512000 Cycles")]
_512k,
[Description("1024000 Cycles")]
_1024k,
[Description("2048000 Cycles")]
_2048k
}

Good-looking mapping
The main idea is that if you use a TypeConverter, you can break the dependency between the name of the enum and what's displayed in your combobox.

In case you didn't knew, here's how you map an enum to a combobox and set/get the selected item::

public partial class MappingEnumToComboboxesForm : Form
{
public MappingEnumToComboboxesForm()
{
InitializeComponent();
//Setting the enums as the data sources of the comboboxes
comboBoxNormal.DataSource =
Enum.GetValues(typeof(WdtOscillatorCycles));
comboBoxImproved.DataSource =
Enum.GetValues(typeof(WdtOscillatorCyclesImproved));
}
public WdtOscillatorCyclesImproved WdtOscillatorCyclesOption
{
get
{
//The result must be cast to the enum's type
return (WdtOscillatorCyclesImproved)(comboBoxImproved.SelectedItem);
}
set
{
//You don't need a cast here.
comboBoxImproved.SelectedItem = value;
}
}
}
Q: Do you know other (better/simpler) methods for mapping enums to comboboxes? Leave me a comment, if so.

See here the example source files
Download here the entire C# code examples collection

Read more about this topic:
http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx

No comments :

Post a Comment