14

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • possible duplicate of [How do I have an enum bound combobox with custom string formatting for enum values?](http://stackoverflow.com/questions/796607/how-do-i-have-an-enum-bound-combobox-with-custom-string-formatting-for-enum-valu) –  Mar 05 '14 at 09:26
  • See **[this answer](http://stackoverflow.com/questions/796607/how-do-i-override-tostring-in-c-enums/796655#796655)** to the question [How do I override ToString in C# enums?](http://stackoverflow.com/questions/796607/how-do-i-override-tostring-in-c-enums/). – John Saunders Jul 18 '09 at 15:33

7 Answers7

15

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • i have do it but now problem is cboSurveyRemarksType.SelectedItem ....i can not set the selected item .....how to do –  Jul 09 '09 at 06:34
  • After replace _ with space cboBLVisual.SelectedItem = Enum.Value; Why not work? –  Jul 09 '09 at 06:43
  • SelectedItem doesn't work because it references the anonymous type that we created with the query, (the type with Value/Text properties), you have to use the SelectedValue property, cboBLVisual.SelectedValue = Enum.Value – Christian C. Salvadó Jul 09 '09 at 07:03
  • cboBLVisual.SelectedValue = Enum.Value this line show me error...message is below Cannot set the SelectedValue in a ListControl with an empty ValueMember. –  Jul 09 '09 at 08:45
  • 1
    How exactly would you use this? I suppose you'd set the result of this LINQ statement to the `DataSource` property. Would you then set the `ValueMember` property to `"Text"`? How would you get the enum value back? I'm not sure how you'd cast the `SelectedItem` back to the anonymous type that resulted from the LINQ statement. – Jeff B Jul 12 '13 at 21:06
6

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.

/// <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();
}
Steve Crane
  • 4,340
  • 5
  • 40
  • 63
4

Try this...

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum))
                           .Cast<MyEnum>()
                           .Select(e => new { Value = e, Description = e.ToString().Replace("_"," ") })
                           .ToList();
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";

...although, I would be more inclined to use a "Description" attribute (as per Steve Crane's answer).

Black Light
  • 2,358
  • 5
  • 27
  • 49
3

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("_", " ");
Kelsey
  • 47,246
  • 16
  • 124
  • 162
1

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

public static class EnumExtensions {

    public static List<string> GetFriendlyNames(this Enum enm) {
        List<string> result = new List<string>();
        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.

0

I like Kelsey's answer although I would use another variable other than 'e' such as 'en' so the answer can be used in event handlers with less hassle; 'e' in event handlers tends to be the EventArgs argument. As for the LINQ and IEnumerable approach, it seems to me to be more complex and difficult to adapt for non-WPF ComboBoxes with .NET 3.5

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
g_g
  • 1
0

I think that this is not very good idea to map internal enum name into user space. What if you refactor your enum value? So I suggest you to take a look at this article (Localizing .NET Enums). Using technique described in this article, you can not only replace '_' with spaces, but also make different enum representation for different languages (using resources).

arbiter
  • 9,447
  • 1
  • 32
  • 43
  • What do you mean by dynamically? You only bind all values into combo box. And article I mentioned perfectly fits into that. – arbiter Jul 09 '09 at 11:13