If you have a range of values in your program, and you want the user to select one of them, the most useful (to him) is a human readable string. Unfortunately, the most useful (to you) is an enum value, and the most commonly available is the enum value name. Which means that the value name has to be carefully selected to fit both the human readable requirement, and the compiler requirement of "no special characters". Such as space.
The alternative is to load a combo box with a set of fixed strings, and then decode them into your enum values later. Which is something I avoid, as I am sure to miss one when I add options to the enum.
This Tip presents a way to fill a ComboBox with human readable strings, and tie them to enum values.
Create your enum, and give human readable Description attributes:
public enum MyEnum
the1st = 1,
[Description("The second one")]
the2nd = 8000,
final = -1,
Then include this static method in your code:
public static void SetEnumValues(ComboBox cb, Type t)
throw new ArgumentException("Only Enum types can be set");
List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
foreach (int i in Enum.GetValues(t))
string name = Enum.GetName(t, i);
string desc = name;
FieldInfo fi = t.GetField(name);
DescriptionAttribute attributes = (DescriptionAttribute)fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
string s = attributes.Description;
desc = s;
list.Add(new KeyValuePair<string, int>(desc, i));
cb.DisplayMember = "Key";
cb.ValueMember = "Value";
cb.DataSource = list;
Call the method to set the values into your ComboBox:
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
The CombBox will now show the values:
The second one
You can now use the values as you wish in your ComboBox events:
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
MyEnum me = (MyEnum)myComboBox.SelectedValue;
The second one
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?