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

前端 未结 28 2157
心在旅途
心在旅途 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 04:51

    public Form1()
    {
        InitializeComponent();
        comboBox.DataSource = EnumWithName.ParseEnum();
        comboBox.DisplayMember = "Name";
    }
    
    public class EnumWithName
    {
        public string Name { get; set; }
        public T Value { get; set; }
    
        public static EnumWithName[] ParseEnum()
        {
            List> 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();
        }
    }
    
    public enum SearchType
    {
        Value_1,
        Value_2
    }
    

提交回复
热议问题