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

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

    Try:

    comboBox1.SelectedItem = MyEnum.Something;
    

    EDITS:

    Whoops, you've tried that already. However, it worked for me when my comboBox was set to be a DropDownList.

    Here is my full code which works for me (with both DropDown and DropDownList):

    public partial class Form1 : Form
    {
        public enum BlahEnum
        { 
            Red,
            Green,
            Blue,
            Purple
        }
    
        public Form1()
        {
            InitializeComponent();
    
            comboBox1.DataSource = Enum.GetValues(typeof(BlahEnum));
    
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            comboBox1.SelectedItem = BlahEnum.Blue;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 04:58

    Convert the enum to a list of string and add this to the comboBox

    comboBox1.DataSource = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
    

    Set the displayed value using selectedItem

    comboBox1.SelectedItem = SomeEnum.SomeValue;
    
    0 讨论(0)
  • 2020-11-28 05:00
        public enum Colors
        {
            Red = 10,
            Blue = 20,
            Green = 30,
            Yellow = 40,
        }
    
    comboBox1.DataSource = Enum.GetValues(typeof(Colors));
    

    Full Source...Binding an enum to Combobox

    0 讨论(0)
  • 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<KeyValuePair<string,object>> 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<TEnum>(this ComboBox comboBox)
        {
            var enumType = typeof(TEnum);
    
            var fields = enumType.GetMembers()
                                  .OfType<FieldInfo>()
                                  .Where(p => p.MemberType == MemberTypes.Field)
                                  .Where(p => p.IsLiteral)
                                  .ToList();
    
            var valuesByName = new Dictionary<string, object>();
    
            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";
        }
    
    
    }
    
    0 讨论(0)
  • 2020-11-28 05:02

    Based on the answer from @Amir Shenouda I end up with this:

    Enum's definition:

    public enum Status { Active = 0, Canceled = 3 }; 
    

    Setting the drop down values from it:

    cbStatus.DataSource = Enum.GetValues(typeof(Status));
    

    Getting the enum from the selected item:

    Status? status = cbStatus.SelectedValue as Status?;
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
提交回复
热议问题