我目前正在开发 C# 应用程序。
我需要使用带有 ComboBox 的枚举来获取选定的月份。我有以下内容来创建枚举:
enum Months
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};
然后我使用以下方法初始化 ComboBox:
cboMonthFrom.Items.AddRange(Enum.GetNames(typeof(Months)));
这段代码工作正常,但问题是当我尝试获取所选月份的所选枚举值时。
为了从组合框中获取枚举值,我使用了以下方法:
private void cboMonthFrom_SelectedIndexChanged(object sender, EventArgs)
{
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
Console.WriteLine("Selected Month: " + (int)selectedMonth);
}
但是,当我尝试运行上面的代码时,它出现了一个错误,提示 A first chance exception of type 'System.InvalidCastException' occurred
。
我做错了什么。
感谢您提供的任何帮助
最佳答案
试试这个
Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem.ToString());
代替
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
更新了正确的更改
关于c# - C# 中的枚举和组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129378/