使用枚举说明绑定Combobox

时间:2016-03-11 09:02:02

标签: c# combobox enums

我已经通过Stackoverflow了解到有一种简单的方法可以使用Enumeration填充组合框:

cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo));

就我而言,我已经为我的枚举定义了一些描述:

 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}

这很有效,但它显示的是价值,而不是描述 我的问题是,我想在组合框中显示枚举的描述,当它有描述时,或者在没有值的情况下显示值。 如果有必要,我可以为没有描述的值添加描述。 Thx提前。

2 个答案:

答案 0 :(得分:15)

试试这个:

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();

为了使其工作,所有值必须具有描述,否则您将获得NullReference异常。希望有所帮助。

答案 1 :(得分:1)

这是我想出的,因为我也需要设置默认值。

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;
        }
    }
}

<强>用法:

cmbFileType.BindEnumToCombobox<FileType>(FileType.Table);

其中cmbFileTypeComboBoxFileTypeenum

相关问题