I'm populating a combo box with custom enum vals:
private enum AlignOptions
{
Left,
Center,
Right
}
. . .
comboBoxAlign1.DataSource = Enum.GetNames(typeof(AlignOptions));
When I try to assign the selected item to a var of that enum type, though:
AlignOptions alignOption;
. . .
alignOption = (AlignOptions)comboBoxAlign1.SelectedItem;
...it blows up with: "System.InvalidCastException was unhandled Message=Specified cast is not valid."
Isn't the item an AlignOptions type?
Dang, I thought I was being clever. Ginosaji is right, and I had to change it to:
alignOptionStr = comboBoxAlign1.SelectedItem.ToString();
if (alignOptionStr.Equals(AlignOptions.Center.ToString()))
{
lblBarcode.TextAlign = ContentAlignment.MiddleCenter;
}
else if (alignOptionStr.Equals(AlignOptions.Left.ToString()))
{
. . .
It's an invalid cast because you do not have an enum, you have the string name representation of the enum. To get that enum back, you need to parse it.
alignOption = (AlignOptions)Enum.Parse(typeof(AlignOptions), (string)comboBoxAlign1.SelectedItem);
You shoul use Enum.GetValues Method to initialize your combobox instead:
comboBoxAlign1.DataSource = Enum.GetValues(typeof(AlignOptions));
Now combobox contains the elements of the enum and
AlignOptions alignOption = (AlignOptions)comboBoxAlign1.SelectedItem;
is a correct cast.
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