Why is this an invalid cast?

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

Upvotes: 4

Views: 770

Answers (3)

horgh
horgh

Reputation: 18534

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.

Upvotes: 3

Meligy
Meligy

Reputation: 36594

Enum.GetNames() returns string[], so each item is a string, not AlignOptions.

You can get the enum value by:

    alignOption = (AlignOptions) Enum.Parse(typeof(AlignOption), 
                                              (string) comboBoxAlign1.SelectedItem);

References:

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126854

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

Upvotes: 8

Related Questions