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

前端 未结 28 2087
心在旅途
心在旅途 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:02

    You can use a extension method

     public static void EnumForComboBox(this ComboBox comboBox, Type enumType)
     {
         var memInfo = enumType.GetMembers().Where(a => a.MemberType == MemberTypes.Field).ToList();
         comboBox.Items.Clear();
         foreach (var member in memInfo)
         {
             var myAttributes = member.GetCustomAttribute(typeof(DescriptionAttribute), false);
             var description = (DescriptionAttribute)myAttributes;
             if (description != null)
             {
                 if (!string.IsNullOrEmpty(description.Description))
                 {
                     comboBox.Items.Add(description.Description);
                     comboBox.SelectedIndex = 0;
                     comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                 }
             }   
         }
     }
    

    How to use ... Declare enum

    using System.ComponentModel;
    
    public enum CalculationType
    {
        [Desciption("LoaderGroup")]
        LoaderGroup,
        [Description("LadingValue")]
        LadingValue,
        [Description("PerBill")]
        PerBill
    }
    

    This method show description in Combo box items

    combobox1.EnumForComboBox(typeof(CalculationType));
    

提交回复
热议问题