DataBinding to Enum Values
When you have an Enum variable, and you want to build a UI to let the user choose one of this values, it's very convenient to show the user the current allowed values of the Enum.
You can avoid duplicate data, doing this... (note it uses reflection, so in high performance environments you should cache this info)
comboBox.DataSource = typeof(YourEnumType).GetFields(BindingFlags.Public);
comboBox.DisplayMember = "Name";
Comments
- Anonymous
February 22, 2005
You can also do:
comboBox.DataSource = Enum.GetValues(typeof(YourEnumType)); - Anonymous
February 22, 2005
Or, you can simply use Enum's GetNames method
comboBox.DataSource = Enum.GetNames(typeof(YourEnumType)); - Anonymous
February 22, 2005
Another option would be to use Enum.GetNames(), which returns an array of strings containing each value of the enum. I'm not sure how it's performance compares to that of using GetFields(), however. - Anonymous
March 17, 2005
Not sure how you managed to get this to work without changing it to:<br><br>comboBox.DataSource = typeof(YourEnumType).GetFields(BindingFlags.Public | BindingFlags.Static);<br><br><br>To quote MSDN<br><br>"You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return."<br><br><br>