Automatically Fill a ComboBox with an Enum

This is a really nice little feature.

If we have an enumerator, say:

public enum MyEnumerator { Oranges, Apples, Hedgehogs, Laptops, Budgies, Other }

Having a form with a ComboBox called comboBox1, put this in the constructor/form load etc:
this.comboBox1.DataSource = Enum.GetValues(typeof(MyEnumerator));

This fills the combobox with the values. To convert the current combobox value back into the enumerator’s value:
MyEnumerator selected = (MyEnumerator)this.comboBox1.SelectedValue;

Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.

This entry was posted in .net, C#, Programming and tagged , , , , , . Bookmark the permalink.

2 Responses to Automatically Fill a ComboBox with an Enum

  1. Sandun says:

    Hey ,
    U can get the Enum value directly as follows
    public enum MyEnumerator {
    Oranges=0, Apples=1, Hedgehogs=2, Laptops=3, Budgies=4, Other=5 }

    int myVariable =(int) (MyEnumerator)this.comboBox1.SelectedValue;
    lblTest.Text=”"+myVariable;

    cheers :)

  2. Richa says:

    Thanks Man!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>