Bind Combobox with Enum Description

倖福魔咒の 提交于 2019-12-21 04:12:46

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/35935961/bind-combobox-with-enum-description

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!