Binding an enum to a control (such as a ComboBox or DataGridView) with a custom string for each enum value


/ Published in: C#
Save to your folder(s)

When you want to put the values of an enumeration into a ComboBox or similar control, there is no obvious or easy way to customize the text displayed.

[UPDATE] The best method I've found is to use a custom TypeConverter. I haven't worked out all the intricacies, but the code below works for combo/listboxes and datagridviews, and I imagine that it would work with all IComponents.

One method below uses the System.ComponentModel.DescriptionAttribute to create a nice description of the enum value and then reads those values using reflection and an extension method (requires .NET 3.5 - see the references for alternatives). Once those values are read, they are put in a Dictionary in order to act as the DataSource for a ComboBox (named w_wifiSecurityIO in the example).

Unfortunately, attributes (to my knowledge) cannot access resources, so the first method does not allow for localization. To overcome this challenge, I have used a Dictionary as the control's Tag and then use the SelectedItem.ToString as the lookup for the enum value selected (works with multiple selections and Flags enums as well, e.g. in a CheckedListBox). The second method uses a Dictionary for the DataSource, sets the DisplayMember and ValueMember properties, then retrieves using the SelectedValue property.

(Since the initialization code is only called once, and there are only a few enum values, the performance hit for using reflection is negligible. Even if it were noticeable, it might still be warranted when compared to other methods of customizing the displayed text.)

The third method comes from the answer to a [StackOverflow question about the subject](http://stackoverflow.com/questions/1415140/c-enums-can-my-enums-have-friendly-names/1415460#1415460) and uses a simple extension method that allows for localization.

Another method is [enumeration classes](http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx).

(Used in RedBird::Hawk.)

References:
[msmvps.com](http://msmvps.com/blogs/deborahk/archive/2009/07/10/enum-binding-to-the-description-attribute.aspx)
[codeproject](http://www.codeproject.com/KB/cs/enumdatabinding.aspx)
[blogs.msdn](http://blogs.msdn.com/abhinaba/archive/2005/10/21/483337.aspx)
[local ms help](ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_system/html/7f153948-1284-313b-1f33-a6ed0d817322.htm) (DescriptionAttribute Class)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.