Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Combobox with Enum Description

Tags:

c#

enums

combobox

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.

like image 826
Dinalan Avatar asked Mar 11 '16 09:03

Dinalan


2 Answers

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.

like image 182
5 revs, 4 users 77%SuperG Avatar answered Sep 28 '22 12:09

5 revs, 4 users 77%SuperG


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.

like image 21
Matt Avatar answered Sep 28 '22 12:09

Matt