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

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

    None of these worked for me, but this did (and it had the added benefit of being able to have a better description for the name of each enum). I'm not sure if it's due to .net updates or not, but regardless I think this is the best way. You'll need to add a reference to:

    using System.ComponentModel;

    enum MyEnum
    {
        [Description("Red Color")]
        Red = 10,
        [Description("Blue Color")]
        Blue = 50
    }
    
    ....
    
        private void LoadCombobox()
        {
            cmbxNewBox.DataSource = Enum.GetValues(typeof(MyEnum))
                .Cast()
                .Select(value => new
                {
                    (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
                    value
                })
                .OrderBy(item => item.value)
                .ToList();
            cmbxNewBox.DisplayMember = "Description";
            cmbxNewBox.ValueMember = "value";
        }
    

    Then when you want to access the data use these two lines:

            Enum.TryParse(cmbxNewBox.SelectedValue.ToString(), out MyEnum proc);
            int nValue = (int)proc;
    

提交回复
热议问题