Display enum in ComboBox with spaces

后端 未结 7 1127
北海茫月
北海茫月 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:50

    If you're using .NET 3.5, you could add this extension class:

    public static class EnumExtensions {
    
        public static List GetFriendlyNames(this Enum enm) {
            List result = new List();
            result.AddRange(Enum.GetNames(enm.GetType()).Select(s => s.ToFriendlyName()));
            return result;
        }
    
        public static string GetFriendlyName(this Enum enm) {
            return Enum.GetName(enm.GetType(), enm).ToFriendlyName();
        }
    
        private static string ToFriendlyName(this string orig) {
            return orig.Replace("_", " ");
        }
    }
    

    And then to set up your combo box you'd just do:

    MyEnum val = MyEnum.My_Value_1;
    comboBox1.DataSource = val.GetFriendlyNames();
    comboBox1.SelectedItem = val.GetFriendlyName();
    

    This should work with any Enum. You'd have to make sure you have a using statement for the namespace that includes the EnumExtensions class.

提交回复
热议问题