C#中的枚举和组合框

Boa*_*rdy 7 c# enums combobox

我目前正在开发一个C#应用程序.

我需要使用带有组合框的枚举来获取所选月份.我有以下内容来创建枚举:

enum Months 
{ 
   January = 1,
   February,
   March,
   April,
   May,
   June,
   July,
   August,
   September,
   October,
   November,
   December 
};
Run Code Online (Sandbox Code Playgroud)

然后我使用以下内容初始化组合框:

cboMonthFrom.Items.AddRange(Enum.GetNames(typeof(Months)));
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常,但问题是当我尝试获取所选月份的选定枚举值

要从组合框中获取枚举器的值,我使用了以下内容:

private void cboMonthFrom_SelectedIndexChanged(object sender, EventArgs) 
{
   Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
   Console.WriteLine("Selected Month: " + (int)selectedMonth);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行上面的代码时,会出现一个错误,指出System.InvalidCastException发生了类型的第一次机会异常.

我做错了什么.

感谢您的任何帮助,您可以提供

Sad*_*ran 7

试试这个

Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem.ToString());
Run Code Online (Sandbox Code Playgroud)

代替

Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
Run Code Online (Sandbox Code Playgroud)

更新了正确的更改


Sno*_*ear 6

问题是你使用字符串名称(Enum.GetNames返回string[])填充组合框,然后尝试将其强制转换为枚举.一种可能的解决方案是:

Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem);
Run Code Online (Sandbox Code Playgroud)

我还会考虑使用.Net的现有月份信息而不是添加你的枚举:

var formatInfo = new System.Globalization.DateTimeFormatInfo();

var months = Enumerable.Range(1, 12).Select(n => formatInfo.MonthNames[n]);
Run Code Online (Sandbox Code Playgroud)


SwD*_*n81 5

尝试

Months selectedMonth = 
    (Months) Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem);
Run Code Online (Sandbox Code Playgroud)