c# - 充满枚举的组合框

标签 c#

如何在 Combobox 中绑定(bind)特定的 Enum

public enum EduTypePublicEnum
  {
    [RMSEnumItem("1", "Properties.Resources.SEduAlumn")]
    Alumn,
    [RMSEnumItem("2", "Properties.Resources.SEduProfesor")]
    Profesor,
    [RMSEnumItem("3", "Properties.Resources.SEduAll")]
    All
  }

  public class EduTypePublic : RMSEnum<EduTypePublicEnum> { };

在我的表单中

public EduAvisosForm()
{
     InitializeComponent();

     this.myComboBox.DataSource = Edu.Consts.EduTypePublic.Enums;
     this.myComboBox.DisplayMember = "Alumn";
     this.myComboBox.ValueMember = "Alumn";
}

但是,有或没有 ValueMember 都会发生错误。当我在没有 ValueMember 的情况下放置此代码时发生错误,要求在我放置它时询问 ValueMember,但不起作用。

“不可能在具有空 ValueMember 的 ListControl 中定义 SelectedValue”

public abstract class RMSEnum<TEnumType>
    {
        protected RMSEnum();

        public static string CodeList { get; }
        public static string[] Codes { get; }
        public static string DescriptionList { get; }
        public static string[] Descriptions { get; }
        public static object[] Enums { get; }

        public static string Code(TEnumType value);
        public static string Description(string code);
        public static string Description(TEnumType value);
        public static TEnumType Enum(string code);
    }

最佳答案

您的数据源项应具有您指定为显示和值成员的属性。例如。字典 KeyValuePairs 具有名为 Key 和 Value 的属性:

 this.myComboBox.DisplayMember = "Value";
 this.myComboBox.ValueMember = "Key";
 this.myComboBox.DataSource = 
      Enum.GetValues(typeof(EduTypePublicEnum))
          .Cast<EduTypePublicEnum>()
          .Select(e => new { 
               Key = e.ToString(), // possibly read localized string
               Value = e
           }).ToList();

关于c# - 充满枚举的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21784202/

相关文章:

c# - dll文件的说明

c# - 获取.MP4文件中的音频和视频流计数及其属性

c# - 如何使用 PowerShell 使用 C# DLL 中存在的类的新对象

c# - 将 Canvas 保存为 SVG

c# - 计划的 Windows 服务中的一致 FTP 超时

c# - 如何匹配 XML 中的元素 - C#

c# - 动态添加的 ASP.Net 按钮无法调用 Click 或 CommandArgument 事件

c# - 使用 LINQ 或 C# 清理字符串中特定 HTML 的算法

c# - 异步调用 webservice 方法

c# - 在 wP7 中停止图像缓存