Binding an enum to a WinForms combo box, and then setting it

前端 未结 28 2106
心在旅途
心在旅途 2020-11-28 04:33

a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:

comboBox1.DataSource = Enum.GetValues(typeof(MyE         


        
28条回答
  •  眼角桃花
    2020-11-28 05:00

    This is probably never going to be seen among all the other responses, but this is the code I came up with, this has the benefit of using the DescriptionAttribute if it exists, but otherwise using the name of the enum value itself.

    I used a dictionary because it has a ready made key/value item pattern. A List> would also work and without the unnecessary hashing, but a dictionary makes for cleaner code.

    I get members that have a MemberType of Field and that are literal. This creates a sequence of only members that are enum values. This is robust since an enum cannot have other fields.

    public static class ControlExtensions
    {
        public static void BindToEnum(this ComboBox comboBox)
        {
            var enumType = typeof(TEnum);
    
            var fields = enumType.GetMembers()
                                  .OfType()
                                  .Where(p => p.MemberType == MemberTypes.Field)
                                  .Where(p => p.IsLiteral)
                                  .ToList();
    
            var valuesByName = new Dictionary();
    
            foreach (var field in fields)
            {
                var descriptionAttribute = field.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;
    
                var value = (int)field.GetValue(null);
                var description = string.Empty;
    
                if (!string.IsNullOrEmpty(descriptionAttribute?.Description))
                {
                    description = descriptionAttribute.Description;
                }
                else
                {
                    description = field.Name;
                }
    
                valuesByName[description] = value;
            }
    
            comboBox.DataSource = valuesByName.ToList();
            comboBox.DisplayMember = "Key";
            comboBox.ValueMember = "Value";
        }
    
    
    }
    

提交回复
热议问题