I would bind the values of an enumeration with a combobox control.
I’ve written this code:
cboPriorLogicalOperator.DataSource = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(p => new { Key = (int)p, Value = p.ToString() })
.ToList();
myComboBox.DisplayMember = "Value";
myComboBox.ValueMember = "Key";
It works well but I wonder if there is a simpler way.
I think your code is beautiful!
The only improvement would be to place the code in an Extension Method.
EDIT:
When I think about it, what you want to do is to use the
Enumas in the definition and not an instance of the enum, which is required by extensions methods.I found this question, which solves it really nicely:
Only you might want to return a
Dictionary<int, string>and not aSelectList, but you get the idea.EDIT2:
Here we go with a code example that covers the case you are looking at.
Or this version perhaps, where the key is an
int