31

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

Community
  • 1
  • 1
vIceBerg
  • 3,939
  • 5
  • 37
  • 52

9 Answers9

28
string[] names = Enum.GetNames (typeof(MyEnum));

Then just populate the dropdown withe the array

albertein
  • 23,752
  • 5
  • 51
  • 57
25

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>();
Ray Hayes
  • 14,395
  • 8
  • 50
  • 76
  • @Ray - I was going to post a link to the same blog post :-) I've used his utility many times over and it works like a charm! – Metro Smurf Sep 30 '08 at 18:43
  • 1
    A few improvements (might take a few comments, I'm afraid): 1) The method could add the "where T : struct" constraint to make the ArgumentException less likely (though still possible). 2) The foreach can use "foreach(T val in enumValArray)" instead of formatting and then reparsing. – Jon Skeet Sep 30 '08 at 20:03
  • If you're using .NET 3.5, this can be done with just: return Enum.GetValues(typeof(T)).Cast(); That doesn't bother building a list, either :) – Jon Skeet Sep 30 '08 at 20:05
  • Thanks Jom.. BTW, got you book -- and once my team return it to me, I'll read it! ;-) They seem to like it... – Ray Hayes Sep 30 '08 at 21:05
  • Ooops, Jon not Jom (and I have to wait 30 seconds to correct!) – Ray Hayes Sep 30 '08 at 21:06
10

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.

Lasse V. Karlsen
  • 350,178
  • 94
  • 582
  • 779
5

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);
    }
}
dtlvd
  • 503
  • 1
  • 7
  • 21
Firas Assaad
  • 22,872
  • 16
  • 57
  • 75
3

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)

rslite
  • 73,388
  • 4
  • 40
  • 45
1

The problem with using enums to populate pull downs is that you cann't have weird characters or spaces in enums. I have some code that extends enums so that you can add any character you want.

Use it like this..

public enum eCarType
{
    [StringValue("Saloon / Sedan")] Saloon = 5,
    [StringValue("Coupe")] Coupe = 4,
    [StringValue("Estate / Wagon")] Estate = 6,
    [StringValue("Hatchback")] Hatchback = 8,
    [StringValue("Utility")] Ute = 1,
}

Bind data like so..

StringEnum CarTypes = new StringEnum(typeof(eCarTypes));
cmbCarTypes.DataSource = CarTypes.GetGenericListValues();

Here is the class that extends the enum.

// Author: Donny V.
// blog: http://donnyvblog.blogspot.com

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace xEnums
{

    #region Class StringEnum

    /// <summary>
    /// Helper class for working with 'extended' enums using <see cref="StringValueAttribute"/> attributes.
    /// </summary>
    public class StringEnum
    {
        #region Instance implementation

        private Type _enumType;
        private static Hashtable _stringValues = new Hashtable();

        /// <summary>
        /// Creates a new <see cref="StringEnum"/> instance.
        /// </summary>
        /// <param name="enumType">Enum type.</param>
        public StringEnum(Type enumType)
        {
            if (!enumType.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", enumType.ToString()));

            _enumType = enumType;
        }

        /// <summary>
        /// Gets the string value associated with the given enum value.
        /// </summary>
        /// <param name="valueName">Name of the enum value.</param>
        /// <returns>String Value</returns>
        public string GetStringValue(string valueName)
        {
            Enum enumType;
            string stringValue = null;
            try
            {
                enumType = (Enum) Enum.Parse(_enumType, valueName);
                stringValue = GetStringValue(enumType);
            }
            catch (Exception) { }//Swallow!

            return stringValue;
        }

        /// <summary>
        /// Gets the string values associated with the enum.
        /// </summary>
        /// <returns>String value array</returns>
        public Array GetStringValues()
        {
            ArrayList values = new ArrayList();
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(attrs[0].Value);

            }

            return values.ToArray();
        }

        /// <summary>
        /// Gets the values as a 'bindable' list datasource.
        /// </summary>
        /// <returns>IList for data binding</returns>
        public IList GetListValues()
        {
            Type underlyingType = Enum.GetUnderlyingType(_enumType);
            ArrayList values = new ArrayList();
            //List<string> values = new List<string>();

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));

            }

            return values;

        }

        /// <summary>
        /// Gets the values as a 'bindable' list<string> datasource.
        ///This is a newer version of 'GetListValues()'
        /// </summary>
        /// <returns>IList<string> for data binding</returns>
        public IList<string> GetGenericListValues()
        {
            Type underlyingType = Enum.GetUnderlyingType(_enumType);
            List<string> values = new List<string>();

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(attrs[0].Value);
            }

            return values;

        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <returns>Existence of the string value</returns>
        public bool IsStringDefined(string stringValue)
        {
            return Parse(_enumType, stringValue) != null;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Existence of the string value</returns>
        public bool IsStringDefined(string stringValue, bool ignoreCase)
        {
            return Parse(_enumType, stringValue, ignoreCase) != null;
        }

        /// <summary>
        /// Gets the underlying enum type for this instance.
        /// </summary>
        /// <value></value>
        public Type EnumType
        {
            get { return _enumType; }
        }

        #endregion

        #region Static implementation

        /// <summary>
        /// Gets a string value for a particular enum value.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
        public static string GetStringValue(Enum value)
        {
            string output = null;
            Type type = value.GetType();

            if (_stringValues.ContainsKey(value))
                output = (_stringValues[value] as StringValueAttribute).Value;
            else 
            {
                //Look for our 'StringValueAttribute' in the field's custom attributes
                FieldInfo fi = type.GetField(value.ToString());
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                {
                    _stringValues.Add(value, attrs[0]);
                    output = attrs[0].Value;
                }

            }
            return output;

        }

        /// <summary>
        /// Parses the supplied enum and string value to find an associated enum value (case sensitive).
        /// </summary>
        /// <param name="type">Type.</param>
        /// <param name="stringValue">String value.</param>
        /// <returns>Enum value associated with the string value, or null if not found.</returns>
        public static object Parse(Type type, string stringValue)
        {
            return Parse(type, stringValue, false);
        }

        /// <summary>
        /// Parses the supplied enum and string value to find an associated enum value.
        /// </summary>
        /// <param name="type">Type.</param>
        /// <param name="stringValue">String value.</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Enum value associated with the string value, or null if not found.</returns>
        public static object Parse(Type type, string stringValue, bool ignoreCase)
        {
            object output = null;
            string enumStringValue = null;

            if (!type.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", type.ToString()));

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in type.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    enumStringValue = attrs[0].Value;

                //Check for equality then select actual enum value.
                if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
                {
                    output = Enum.Parse(type, fi.Name);
                    break;
                }
            }

            return output;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="enumType">Type of enum</param>
        /// <returns>Existence of the string value</returns>
        public static bool IsStringDefined(Type enumType, string stringValue)
        {
            return Parse(enumType, stringValue) != null;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="enumType">Type of enum</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Existence of the string value</returns>
        public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
        {
            return Parse(enumType, stringValue, ignoreCase) != null;
        }

        #endregion
    }

    #endregion

    #region Class StringValueAttribute

    /// <summary>
    /// Simple attribute class for storing String Values
    /// </summary>
    public class StringValueAttribute : Attribute
    {
        private string _value;

        /// <summary>
        /// Creates a new <see cref="StringValueAttribute"/> instance.
        /// </summary>
        /// <param name="value">Value.</param>
        public StringValueAttribute(string value)
        {
            _value = value;
        }

        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <value></value>
        public string Value
        {
            get { return _value; }
        }
    }

    #endregion
}
dtlvd
  • 503
  • 1
  • 7
  • 21
Donny V.
  • 19,411
  • 13
  • 59
  • 76
1

.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.

Michael Damatov
  • 13,992
  • 10
  • 43
  • 70
0

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;
JosephStyons
  • 53,646
  • 63
  • 151
  • 228
  • Except there is no C# syntax matching that, so the other examples are probably better! Personally I don't think min/max suit an enum, if I were defining a traffic light, I want Red, Amber, Green not Min, Red, Amber, Green, Min. – Ray Hayes Sep 30 '08 at 18:24
  • Erm... ... Green, Max. (oops) – Ray Hayes Sep 30 '08 at 18:24
0

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;
Programmin Tool
  • 6,237
  • 11
  • 46
  • 67