且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用枚举说明绑定组合框

更新时间:2023-10-14 15:54:28

尝试以下操作:

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例外。希望有帮助。

In order for this to work, all the values must have a description or you'll get a NullReference Exception. Hope that helps.