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(MyE
This worked for me:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
comboBox1.SelectedIndex = comboBox1.FindStringExact(MyEnum.something.ToString());
Try this:
// fill list
MyEnumDropDownList.DataSource = Enum.GetValues(typeof(MyEnum));
// binding
MyEnumDropDownList.DataBindings.Add(new Binding("SelectedValue", StoreObject, "StoreObjectMyEnumField"));
StoreObject is my object example with StoreObjectMyEnumField property for store MyEnum value.
You could use the "FindString.." functions:
Public Class Form1
Public Enum Test
pete
jack
fran
bill
End Enum
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = [Enum].GetValues(GetType(Test))
ComboBox1.SelectedIndex = ComboBox1.FindStringExact("jack")
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Test.jack.ToString())
ComboBox1.SelectedIndex = ComboBox1.FindStringExact([Enum].GetName(GetType(Test), Test.jack))
ComboBox1.SelectedItem = Test.bill
End Sub
End Class
You can use a list of KeyValuePair values as the datasource for the combobox. You will need a helper method where you can specify the enum type and it returns IEnumerable> where int is the value of enum and string is the name of the enum value. In your combobox, set, DisplayMember property to 'Key' and ValueMember property to 'Value'. Value and Key are public properties of KeyValuePair structure. Then when you set SelectedItem property to an enum value like you are doing, it should work.
only use casting this way:
if((YouEnum)ComboBoxControl.SelectedItem == YouEnum.Español)
{
//TODO: type you code here
}
The code
comboBox1.SelectedItem = MyEnum.Something;
is ok, the problem must reside in the DataBinding. DataBinding assignments occur after the constructor, mainly the first time the combobox is shown. Try to set the value in the Load event. For example, add this code:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
comboBox1.SelectedItem = MyEnum.Something;
}
And check if it works.