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

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

     public static void FillByEnumOrderByNumber(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
    
            var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
                         select
                            new
                             KeyValuePair(   (enumValue), enumValue.ToString());
    
            ctrl.DataSource = values
                .OrderBy(x => x.Key)
    
                .ToList();
    
            ctrl.DisplayMember = "Value";
            ctrl.ValueMember = "Key";
    
            ctrl.SelectedValue = enum1;
        }
        public static void  FillByEnumOrderByName(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true  ) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
    
            var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
                         select 
                            new 
                             KeyValuePair ( (enumValue),  enumValue.ToString()  );
    
            ctrl.DataSource = values
                .OrderBy(x=>x.Value)
                .ToList();
    
            ctrl.DisplayMember = "Value";
            ctrl.ValueMember = "Key";
    
            ctrl.SelectedValue = enum1;
        }
    

提交回复
热议问题