I have seen through Stackoverflow that there is an easy way to populate a combobox with an Enumeration:
cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo))
Here is what I came up with since I needed to set the default as well.
public static void BindEnumToCombobox(this ComboBox comboBox, T defaultSelection)
{
var list = Enum.GetValues(typeof(T))
.Cast()
.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.Table);
Where cmbFileType
is the ComboBox
and FileType
is the enum
.