Binding an enum to a WinForms combo box, and then setting it

Tony Miletto picture Tony Miletto · May 25, 2009 · Viewed 186.3k times · Source

a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

But that is pretty useless without being able to set the actual value to display.

I have tried:

comboBox1.SelectedItem = MyEnum.Something; // Does not work. SelectedItem remains null

I have also tried:

comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something); // ArgumentOutOfRangeException, SelectedIndex remains -1

Does anyone have any ideas how to do this?

Answer

Amir Shenouda picture Amir Shenouda · Mar 2, 2012

The Enum

public enum Status { Active = 0, Canceled = 3 }; 

Setting the drop down values from it

cbStatus.DataSource = Enum.GetValues(typeof(Status));

Getting the enum from the selected item

Status status; 
Enum.TryParse<Status>(cbStatus.SelectedValue.ToString(), out status);