Bind Enum values to a .NET WinForm ComboBox

This is how we can bind a list of Enumvalues to a drop down list.

Create this generic class that returns a list of key/value of an Enum:


public class EnumWithName
{
        public string Name { get; set; }
        public T Value { get; set; }

        public static EnumWithName[] ParseEnum()
        {
            var list = new List>();
            foreach (object o in Enum.GetValues(typeof(T)))
            {
                list.Add(new EnumWithName
                {
                    Name = Enum.GetName(typeof(T), o).Replace('_', ' '),
                    Value = (T)o
                });
            }

            return list.ToArray();
        }
 }

Then use it like this:


myCombo.DataSource = EnumWithName.ParseEnum();
myCombo.DisplayMember = "Name";
myCombo.ValueMember = "Value";

Post a Comment

Previous Post Next Post