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.
DisplayMember = "Name"; comboBox1. ValueMember = "Name"; To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1. SelectedItem; .
An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy. enum Season { Spring, Summer, Autumn, Winter }
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();
}
}
Why not to use:
myComboBox.DataSource = Enum.GetValues(typeof(MyEnum))
?
foreach (int r in Enum.GetValues(typeof(MyEnum)))
{
var item = new ListItem(Enum.GetName(typeof(MyEnum), r), r.ToString());
ddl.Items.Add(item);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With