Possible Duplicate:
C#: How to enumerate an enum?
The subject says all. I want to use that to add the values of an enum in a combobox.
Thanks
vIceBerg
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
Yes. Use GetValues() method in System. Enum class.
string[] names = Enum.GetNames (typeof(MyEnum));
Then just populate the dropdown withe the array
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>();
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