Bind Combobox with Enum Description

I saw through Stackoverflow that there is an easy way to populate combobox with Enumeration:

cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo)); 

In my case, I defined some description for my enumerations:

  public enum TiposTrabajo { [Description("Programacion Otros")] ProgramacionOtros = 1, Especificaciones = 2, [Description("Pruebas Taller")] PruebasTaller = 3, [Description("Puesta En Marcha")] PuestaEnMarcha = 4, [Description("Programación Control")] ProgramacionControl = 5} 

This works very well, but it shows the value, not the description. My problem is that I want to show the description of the enumeration in combobox when it has a description or value in case it does not matter. If necessary, I can add a description for values ​​that do not have a description. thanks in advance.

+7
enums c # combobox
source share
2 answers

Try the following:

 cbTipos.DisplayMember = "Description"; cbTipos.ValueMember = "Value"; cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo)) .Cast<Enum>() .Select(value => new { (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description, value }) .OrderBy(item => item.value) .ToList(); 

For this to work, all values ​​must have a description or you will get a NullReference exception. Hope this helps.

+13
source share

This is what I came up with, as I also needed to set a default value.

 public static void BindEnumToCombobox<T>(this ComboBox comboBox, T defaultSelection) { var list = Enum.GetValues(typeof(T)) .Cast<T>() .Select(value => new { (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description, value }) .OrderBy(item => item.value.ToString()) .ToList(); comboBox.DataSource = list; comboBox.DisplayMember = "Description"; comboBox.ValueMember = "value"; foreach (var opts in list) { if (opts.value.ToString() == defaultSelection.ToString()) { comboBox.SelectedItem = opts; } } } 

Application:

 cmbFileType.BindEnumToCombobox<FileType>(FileType.Table); 

Where cmbFileType is a ComboBox and "FileType" is an enumeration.

0
source share

All Articles