Display enum values ​​inside winforms combobox

Say I have the following enum

public enum MyMode { A = 1, B = 2, C = 3, D = 4 }; 

and I want to use this enumeration as a list of values ​​inside a combobox, I tried using

 cmbMyMode.Items.Add(Enum.GetValues(typeof(MyMode ))); 

but i get the following

 MyMode[] Array 

I need to display A, B, C, D, and is it possible to use a custom string instead of A, B, C, D

thanks

+4
source share
3 answers
 List<MyMode> modes = Enum.GetValues(typeof(MyMode)).Cast<MyMode>().ToList(); cmbMyMode.DataSource = modes; 

And for setting labels:

 var modes = Enum.GetValues(typeof(MyMode)).Cast<MyMode>().Select(mode => new { Value = mode, Title = string.Format("-->{0}<--", mode) }). ToList(); cmbMyMode.ValueMember = "Value"; cmbMyMode.DisplayMember = "Title"; cmbMyMode.DataSource = modes; 

and then

 cmbMyMode.SelectedValue 
+13
source
  cmbMyMode.Items.AddRange(Enum.GetNames(typeof(MyMode))); 
+3
source
 foreach (var name in Enum.GetNames(typeof(MyMode))) { cmbMyMode.Items.Add(name); } 
+1
source

Source: https://habr.com/ru/post/1482523/


All Articles