4

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

3 回答 3

8

这是一个无效的转换,因为你没有枚举,你有枚举的字符串名称表示。要取回该枚举,您需要对其进行解析。

alignOption = (AlignOptions)Enum.Parse(typeof(AlignOptions), (string)comboBoxAlign1.SelectedItem);
于 2013-02-15T00:27:04.253 回答
3

您应该使用Enum.GetValues 方法来初始化您的组合框:

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

现在组合框包含枚举的元素和

AlignOptions alignOption = (AlignOptions)comboBoxAlign1.SelectedItem;

是正确的演员表。

于 2013-02-15T00:39:09.297 回答
1

Enum.GetNames()返回string[],所以每个项目都是 a string,而不是AlignOptions

您可以通过以下方式获取枚举值:

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

参考:

于 2013-02-15T00:27:17.060 回答