Kristian Vukusic
Kristian Vukusic

Reputation: 3324

Binding to enums

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.

Upvotes: 1

Views: 1943

Answers (2)

Agustin Meriles
Agustin Meriles

Reputation: 4854

Try using

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

or

Enum.GetValues(typeof(SportName)) // returns int[]

Upvotes: 3

Bobson
Bobson

Reputation: 13706

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>();

Upvotes: 1

Related Questions