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

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

    The Enum

    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; 
    Enum.TryParse<Status>(cbStatus.SelectedValue.ToString(), out status); 
    
    0 讨论(0)
  • 2020-11-28 04:50

    Old question perhaps here but I had the issue and the solution was easy and simple, I found this http://www.c-sharpcorner.com/UploadFile/mahesh/1220/

    It makes use of the databining and works nicely so check it out.

    0 讨论(0)
  • 2020-11-28 04:51
    public Form1()
    {
        InitializeComponent();
        comboBox.DataSource = EnumWithName<SearchType>.ParseEnum();
        comboBox.DisplayMember = "Name";
    }
    
    public class EnumWithName<T>
    {
        public string Name { get; set; }
        public T Value { get; set; }
    
        public static EnumWithName<T>[] ParseEnum()
        {
            List<EnumWithName<T>> list = new List<EnumWithName<T>>();
    
            foreach (object o in Enum.GetValues(typeof(T)))
            {
                list.Add(new EnumWithName<T>
                {
                    Name = Enum.GetName(typeof(T), o).Replace('_', ' '),
                    Value = (T)o
                });
            }
    
            return list.ToArray();
        }
    }
    
    public enum SearchType
    {
        Value_1,
        Value_2
    }
    
    0 讨论(0)
  • 2020-11-28 04:55
    comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
    
    comboBox1.SelectedIndex = (int)MyEnum.Something;
    
    comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something);
    

    Both of these work for me are you sure there isn't something else wrong?

    0 讨论(0)
  • 2020-11-28 04:55

    That was always a problem. if you have a Sorted Enum, like from 0 to ...

    public enum Test
          one
          Two
          Three
     End
    

    you can bind names to combobox and instead of using .SelectedValue property use .SelectedIndex

       Combobox.DataSource = System.Enum.GetNames(GetType(test))
    

    and the

    Dim x as byte = 0
    Combobox.Selectedindex=x
    
    0 讨论(0)
  • 2020-11-28 04:55

    In Framework 4 you can use the following code:

    To bind MultiColumnMode enum to combobox for example:

    cbMultiColumnMode.Properties.Items.AddRange(typeof(MultiColumnMode).GetEnumNames());
    

    and to get selected index:

    MultiColumnMode multiColMode = (MultiColumnMode)cbMultiColumnMode.SelectedIndex;
    

    note: I use DevExpress combobox in this example, you can do the same in Win Form Combobox

    0 讨论(0)
提交回复
热议问题