Why is this an invalid listing?

I fill out 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 element to the var variable of this enum type, however:

  AlignOptions alignOption; . . . alignOption = (AlignOptions)comboBoxAlign1.SelectedItem; 

... it explodes: "System.InvalidCastException was unhandled. Message = The specified cast is invalid."

Is the type AlignOptions?

UPDATE

Dang, I thought I was smart. 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())) { . . . 
+4
source share
3 answers

Instead, you use the Enum.GetValues ​​Method to initialize the pivot table:

 comboBoxAlign1.DataSource = Enum.GetValues(typeof(AlignOptions)); 

Combobox now contains enumeration and

 AlignOptions alignOption = (AlignOptions)comboBoxAlign1.SelectedItem; 

- the correct selection.

+3
source

This is an incorrect listing because you do not have an enumeration, you have a representation of the name of an enumeration string. To get this listing back, you need to parse it.

 alignOption = (AlignOptions)Enum.Parse(typeof(AlignOptions), (string)comboBoxAlign1.SelectedItem); 
+8
source

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

You can get the enumeration value with:

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

Literature:

+1
source

All Articles