Combobox充满了Enum

时间:2014-02-14 16:15:02

标签: c#

如何绑定Enum中的特定Combobox

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时出错,无效。

"Is not possible define SelectedValue in a ListControl with empty ValueMember"

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

1 个答案:

答案 0 :(得分:0)

您的数据源项应具有您指定为显示和值成员的属性。例如。字典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();