简体   繁体   中英

Bind Combobox with Enum Description

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM