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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With