tags:

views:

2245

answers:

9

Hi!

The subject says all. I want to use that to add the values of an enum in a combobox.

Thanks

vIceBerg

+18  A: 
string[] names = Enum.GetNames (typeof(MyEnum));

Then just populate the dropdown withe the array

AlbertEin
A: 

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
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
Erm... ... Green, Max. (oops)
Ray Hayes
+4  A: 

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);
}
}
Firas Assaad
+8  A: 

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
+2  A: 

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
+18  A: 

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
@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
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
If you're using .NET 3.5, this can be done with just:return Enum.GetValues(typeof(T)).Cast<T>();That doesn't bother building a list, either :)
Jon Skeet
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
Ooops, Jon not Jom (and I have to wait 30 seconds to correct!)
Ray Hayes
A: 

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
A: 
Donny V.
+1  A: 

.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