Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I bind a ComboBox in Windows form?

To bind a ComboBox or ListBox control If you are binding to a table, set the DisplayMember property to the name of a column in the data source. If you are binding to an IList, set the display member to a public property of the type in the list.

Can we assign value to enum in C#?

A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong.

Can enum inherit from another enum C#?

Enums cannot inherit from other enums. In fact all enums must actually inherit from System. Enum . C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.


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); 

To simplify:

First Initialize this command: (e.g. after InitalizeComponent())

yourComboBox.DataSource =  Enum.GetValues(typeof(YourEnum));

To retrieve selected item on combobox:

YourEnum enum = (YourEnum) yourComboBox.SelectedItem;

If you want to set value for the combobox:

yourComboBox.SelectedItem = YourEnem.Foo;

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.


Try:

comboBox1.SelectedItem = MyEnum.Something;

EDITS:

Whoops, you've tried that already. However, it worked for me when my comboBox was set to be a DropDownList.

Here is my full code which works for me (with both DropDown and DropDownList):

public partial class Form1 : Form
{
    public enum BlahEnum
    { 
        Red,
        Green,
        Blue,
        Purple
    }

    public Form1()
    {
        InitializeComponent();

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

    }

    private void button1_Click(object sender, EventArgs e)
    {
        comboBox1.SelectedItem = BlahEnum.Blue;
    }
}