Bind Combobox with Enum Description

后端 未结 2 1426
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 23:18

I have seen through Stackoverflow that there is an easy way to populate a combobox with an Enumeration:

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


        
相关标签:
2条回答
  • 2021-02-13 23:43

    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.

    0 讨论(0)
  • 2021-02-13 23:45

    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.

    0 讨论(0)
提交回复
热议问题