1

Is there a way to bind a combobox to an enum, since there are no methods to get all the values of enums?

My enum is like this:

public enum SportName
{
    [Display(Name = "football", Description = "Football")]
    Football,

    [Display(Name = "table-tennis", Description = "Table Tennis")]
    TableTennis

}

I have a method that is retrieving the attributes. My problem is how to bind these values to a ComboBox and the combobox shoul display the Description for each item.

For me, finding a way to iterate through the enum and creating some kind of a list would be enough but I dont know how to do that.

Kristian Vukusic
  • 3,284
  • 6
  • 30
  • 46

2 Answers2

3

Try using

Enum.GetNames(typeof(SportName)) // returns string[]

or

Enum.GetValues(typeof(SportName)) // returns int[]
Jason Watkins
  • 3,766
  • 1
  • 25
  • 39
Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
  • I think you swapped the return types there. GetNames should be the one returning `string[]` :) – Jason Watkins Mar 21 '13 at 21:04
  • `GetValues` actually returns all the members of the enum, so it's `Enum[]`, which is convertible to and from an `int[]`. – Bobson Mar 21 '13 at 21:09
1

This is from my EnumComboBox class, which inherits from ComboBox

public Type EnumType { get; private set; }
public void SetEnum<T>(T defaultValue) where T : struct, IConvertible
{
    SetEnum(typeof(T));
    this.Text = (defaultValue as Enum).GetLabel();
}
public void SetEnum<T>() where T : struct, IConvertible
{
    SetEnum(typeof(T));
}
private void SetEnum(Type type)
{
    if (type.IsEnum)
    {
        EnumType = type;
        ValueMember = "Value";
        DisplayMember = "Display";
        var data = Enum.GetValues(EnumType).Cast<Enum>().Select(x => new
        {
            Display = x.GetLabel(), // GetLabel is a function to get the text-to-display for the enum
            Value = x,
        }).ToList();
        DataSource = data;
        this.Text = data.First().Display;
    }
    else
    {
        EnumType = null;
    }
}

public T EnumValue<T>() where T : struct, IConvertible
{
    if (typeof (T) != EnumType) throw new InvalidCastException("Can't convert value from " + EnumType.Name + " to " + typeof (T).Name);

    return (T)this.SelectedValue;
}

You can't set it at design-time, but when you initalize the box you can just call

myCombo.SetEnum<SportName>();

and then later to get the value

var sport = myCombo.EnumValue<SportName>();
Bobson
  • 13,498
  • 5
  • 55
  • 80