How do I have an enum bound combobox with custom string formatting for enum values?

Shalom Craimer picture Shalom Craimer · Apr 28, 2009 · Viewed 85.3k times · Source

In the post Enum ToString, a method is described to use the custom attribute DescriptionAttribute like this:

Enum HowNice {
  [Description("Really Nice")]
  ReallyNice,
  [Description("Kinda Nice")]
  SortOfNice,
  [Description("Not Nice At All")]
  NotNice
}

And then, you call a function GetDescription, using syntax like:

GetDescription<HowNice>(NotNice); // Returns "Not Nice At All"

But that doesn't really help me when I want to simply populate a ComboBox with the values of an enum, since I cannot force the ComboBox to call GetDescription.

What I want has the following requirements:

  • Reading (HowNice)myComboBox.selectedItem will return the selected value as the enum value.
  • The user should see the user-friendly display strings, and not just the name of the enumeration values. So instead of seeing "NotNice", the user would see "Not Nice At All".
  • Hopefully, the solution will require minimal code changes to existing enumerations.

Obviously, I could implement a new class for each enum that I create, and override its ToString(), but that's a lot of work for each enum, and I'd rather avoid that.

Any ideas?

Heck, I'll even throw in a hug as a bounty :-)

Answer

Anton Gogolev picture Anton Gogolev · Apr 28, 2009

ComboBox has everything you need: the FormattingEnabled property, which you should set to true, and Format event, where you'll need to place desired formatting logic. Thus,

myComboBox.FormattingEnabled = true;
myComboBox.Format += delegate(object sender, ListControlConvertEventArgs e)
    {
        e.Value = GetDescription<HowNice>((HowNice)e.Value);
    }