Hi!
The subject says all. I want to use that to add the values of an enum in a combobox.
Thanks
vIceBerg
Hi!
The subject says all. I want to use that to add the values of an enum in a combobox.
Thanks
vIceBerg
string[] names = Enum.GetNames (typeof(MyEnum));
Then just populate the dropdown withe the array
It is often useful to define a Min and Max inside your enum, which will always be the first and last items. Here is a very simple example using Delphi syntax:
procedure TForm1.Button1Click(Sender: TObject);
type
TEmployeeTypes = (etMin, etHourly, etSalary, etContractor, etMax);
var
i : TEmployeeTypes;
begin
for i := etMin to etMax do begin
//do something
end;
end;
You could iterate through the array returned by the Enum.GetNames method instead.
public class GetNamesTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
public static void Main() {
Console.WriteLine("The values of the Colors Enum are:");
foreach(string s in Enum.GetNames(typeof(Colors)))
Console.WriteLine(s);
Console.WriteLine();
Console.WriteLine("The values of the Styles Enum are:");
foreach(string s in Enum.GetNames(typeof(Styles)))
Console.WriteLine(s);
}
}
Use the Enum.GetValues method:
foreach (TestEnum en in Enum.GetValues(typeof(TestEnum)))
{
...
}
You don't need to cast them to a string, and that way you can just retrieve them back by casting the SelectedItem property to a TestEnum value directly as well.
If you need the values of the combo to correspond to the values of the enum you can also use something like this:
foreach (TheEnum value in Enum.GetValues(typeof(TheEnum)))
dropDown.Items.Add(new ListItem(
value.ToString(), ((int)value).ToString()
);
In this way you can show the texts in the dropdown and obtain back the value (in SelectedValue property)
I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that doesn't match your coding standards)
This blog entry may be useful - Associating Strings with enums in c#
public enum States
{
California,
[Description("New Mexico")]
NewMexico,
[Description("New York")]
NewYork,
[Description("South Carolina")]
SouthCarolina,
Tennessee,
Washington
}
As a bonus, he also supplied a utility method for enumerating the enumeration that I've now updated with Jon Skeet's comments
public static IEnumerable<T> EnumToList<T>()
where T : struct
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>();
foreach (T val in enumValArray)
{
enumValList.Add(val.ToString());
}
return enumValList;
}
Jon also pointed out that in C# 3.0 it can be simplified to something like this (which is now getting so light-weight that I'd imagine you could just do it in-line):
public static IEnumerable<T> EnumToList<T>()
where T : struct
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
// Using above method
statesComboBox.Items = EnumToList<States>();
// Inline
statesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>();
Little more "complicated" (maybe overkill) but I use these two methods to return dictionaries to use as datasources. The first one returns the name as key and the second value as key.
public static IDictionary<string, int> ConvertEnumToDictionaryNameFirst<K>() { if (typeof(K).BaseType != typeof(Enum)) { throw new InvalidCastException(); } return Enum.GetValues(typeof(K)).Cast<int>().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem)); }
Or you could do
public static IDictionary<int, string> ConvertEnumToDictionaryValueFirst<K>() { if (typeof(K).BaseType != typeof(Enum)) { throw new InvalidCastException(); } return Enum.GetNames(typeof(K)).Cast<string>().ToDictionary(currentItem => (int)Enum.Parse(typeof(K), currentItem)); }
This assumes you are using 3.5 though. You'd have to replace the lambda expressions if not.
Use:
Dictionary list = ConvertEnumToDictionaryValueFirst<SomeEnum>();
using System; using System.Collections.Generic; using System.Linq;
.NET 3.5 makes it simple by using extension methods:
enum Color {Red, Green, Blue}
Can be iterated with
Enum.GetValues(typeof(Color)).Cast<Color>()
or define a new static generic method:
static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
Keep in mind that iterating with the Enum.GetValues() method uses reflection and thus has performance penalties.