Why is this an invalid cast?

c#, casting, combobox, enums, selecteditem

Solution

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.

Problem

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? UPDATE 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())) { . . . ```

Original source