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()))
{
. . .
You shoul use Enum.GetValues Method to initialize your combobox instead:
Now combobox contains the elements of the enum and
is a correct cast.