Display enum in ComboBox with spaces

后端 未结 7 1062
北海茫月
北海茫月 2020-12-31 06:03

I have an enum, example:

enum MyEnum
{
My_Value_1,
My_Value_2
}

With :

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum)         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 06:57

    If you are able to modify the code defining the enum, so you could add attributes to the values without modifying the actual enum values, then you could use this extension method.

    /// 
    /// Retrieve the description of the enum, e.g.
    /// [Description("Bright Pink")]
    /// BrightPink = 2,
    /// 
    /// 
    /// The friendly description of the enum.
    public static string GetDescription(this Enum value)
    {
      Type type = value.GetType();
    
      MemberInfo[] memInfo = type.GetMember(value.ToString());
    
      if (memInfo != null && memInfo.Length > 0)
      {
        object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
        if (attrs != null && attrs.Length > 0)
        {
          return ((DescriptionAttribute)attrs[0]).Description;
        }
      }
    
      return value.ToString();
    }
    

提交回复
热议问题