I have seen through Stackoverflow that there is an easy way to populate a combobox with an Enumeration:
cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo));
In my case I have 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 is working pretty well, but it shows the value, not the description My problem is that I want to show in the combobox the description of the enumeration when it have a description or the value in the case it doesn't have value. If it's necessary I can add a description for the values that doesn't have description. Thx in advance.
Try this:
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();
In order for this to work, all the values must have a description or you'll get a NullReference Exception. Hope that helps.
Here is what I came up with since I needed to set the default as well.
public static void BindEnumToCombobox<T>(this ComboBox comboBox, T defaultSelection)
{
var list = Enum.GetValues(typeof(T))
.Cast<T>()
.Select(value => new
{
Description = (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute)?.Description ?? value.ToString(),
Value = 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;
}
}
}
Usage:
cmbFileType.BindEnumToCombobox<FileType>(FileType.Table);
Where cmbFileType
is the ComboBox
and FileType
is the enum
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With