How to bind an enumeration to combobox
Why not to use:
myComboBox.DataSource = Enum.GetValues(typeof(MyEnum))
?
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 Enum
as 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:
public class SelectList
{
// Normal SelectList properties/methods go here
public static SelectList Of<T>()
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = from Enum e in Enum.GetValues(t)
select new { ID = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name");
}
return null;
}
}
// called with
var list = SelectList.Of<Things>();
Only you might want to return a Dictionary<int, string>
and not a SelectList
, but you get the idea.
EDIT2:
Here we go with a code example that covers the case you are looking at.
public class EnumList
{
public static IEnumerable<KeyValuePair<T, string>> Of<T>()
{
return Enum.GetValues(typeof (T))
.Cast<T>()
.Select(p => new KeyValuePair<T, string>(p, p.ToString()))
.ToList();
}
}
Or this version perhaps, where the key is an int
public class EnumList
{
public static IEnumerable<KeyValuePair<int, string>> Of<T>()
{
return Enum.GetValues(typeof (T))
.Cast<T>()
.Select(p => new KeyValuePair<int, string>(Convert.ToInt32(p), p.ToString()))
.ToList();
}
}
foreach (int r in Enum.GetValues(typeof(MyEnum)))
{
var item = new ListItem(Enum.GetName(typeof(MyEnum), r), r.ToString());
ddl.Items.Add(item);
}