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 (4)

  1. You can also do:

    comboBox.DataSource = Enum.GetValues(typeof(YourEnumType));

  2. Or, you can simply use Enum’s GetNames method

    comboBox.DataSource = Enum.GetNames(typeof(YourEnumType));

  3. Andy says:

    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.

  4. Johnny Hall says:

    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>&quot;You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.&quot;
    <br>
    <br>
    <br>