枚举和组合框中C# [英] Enums and Combo Boxes in C#
问题描述
我目前正在开发一个C#应用程序。
I am currently developing a C# application.
我需要使用带有组合框的枚举来获取所选择的月份。我有以下创建枚举:
I need to use an enum with a combo box 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
};
然后我使用以下命令初始化组合框:
I then initialise the combobox using the following:
cboMonthFrom.Items.AddRange(Enum.GetNames(typeof(Months)));
这一段代码工作正常,但问题是当我尝试获取所选的枚举值
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 value the enumerator from the combo box 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.
我做错了。
感谢您提供任何帮助
推荐答案
b
$ b
Try this
Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem.ToString());
而不是
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
更新时正确更改
这篇关于枚举和组合框中C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!