C#中的枚举和组合框 [英] Enums and ComboBoxes in C#
问题描述
我目前正在开发C#应用程序。
I am currently developing a C# application.
我需要使用带有ComboBox的枚举来获取选定的月份。我用以下方法创建枚举:
I need to use an Enum with a ComboBox to get the selected month. I have the following to create the Enum:
enum Months
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};
然后我使用以下命令初始化ComboBox:
I then initialise the ComboBox using the following:
cboMonthFrom.Items.AddRange(Enum.GetNames(typeof(Months)));
这段代码可以正常工作,但是问题是当我尝试获取所选的Enum值时
This bit of code works fine however the problem is when I try to get the selected Enum value for the selected month.
要从组合框获取枚举值,我使用了以下内容:
To get the Enum value from the ComboBox I have used the following:
private void cboMonthFrom_SelectedIndexChanged(object sender, EventArgs)
{
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
Console.WriteLine("Selected Month: " + (int)selectedMonth);
}
但是,当我尝试运行上面的代码时会出现错误说发生类型为'System.InvalidCastException'的第一次机会异常。
However, when I try to run the code above it comes up with an error saying A first chance exception of type 'System.InvalidCastException' occurred
.
我做错了。
感谢您可以提供的任何帮助
Thanks for any help you can provide
推荐答案
尝试一下
Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem.ToString());
而不是
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
已进行了正确的更改
这篇关于C#中的枚举和组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!