Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()))
    {
        . . .
like image 487
B. Clay Shannon-B. Crow Raven Avatar asked Dec 15 '22 14:12

B. Clay Shannon-B. Crow Raven


2 Answers

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);
like image 90
Anthony Pegram Avatar answered Jan 02 '23 19:01

Anthony Pegram


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.

like image 37
horgh Avatar answered Jan 02 '23 20:01

horgh