Display enum in ComboBox with spaces

I have an enum, example:

enum MyEnum
{
My_Value_1,
My_Value_2
}

With :

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

But now my question: How can I replace the "_" with " " so that it becomes items with spaces instead of underscores? And that a databound object still works


If you have access to the Framework 3.5, you could do something like this:

Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(e=> new
                {
                    Value = e,
                    Text = e.ToString().Replace("_", " ")
                });

This will return you an IEnumerable of an anonymous type, that contains a Value property, that is the enumeration type itself, and a Text property, that will contain the string representation of the enumerator with the underscores replaced with space.

The purpose of the Value property is that you can know exactly which enumerator was chosen in the combo, without having to get the underscores back and parse the string.


如果您可以修改定义枚举的代码,那么您可以在不修改实际枚举值的情况下向这些值添加属性,那么您可以使用此扩展方法。

/// <summary>
/// Retrieve the description of the enum, e.g.
/// [Description("Bright Pink")]
/// BrightPink = 2,
/// </summary>
/// <param name="value"></param>
/// <returns>The friendly description of the enum.</returns>
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();
}

Fill the combobox manually and do a string replace on the enum.

Here is exactly what you need to do:

comboBox1.Items.Clear();
MyEnum[] e = (MyEnum[])(Enum.GetValues(typeof(MyEnum)));
for (int i = 0; i < e.Length; i++)
{
    comboBox1.Items.Add(e[i].ToString().Replace("_", " "));
}

To set the selected item of the combobox do the following:

comboBox1.SelectedItem = MyEnum.My_Value_2.ToString().Replace("_", " ");
链接地址: http://www.djcxy.com/p/91504.html

上一篇: 循环访问C#枚举的键和值

下一篇: 用空格在ComboBox中显示枚举