c# - C# 中的枚举和组合框

标签 c# enums combobox

我目前正在开发 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/

相关文章:

c# - 无法使用 rabbitMQ 加载 System.Threading.Tasks.Extensions 4.2.0.0

javascript - 如何在 Angular 5 中使用枚举

c# - ComboBox - 自动完成 + 自由打字

javascript - 过滤组合中的服务器端选项

java - 使用枚举组合框中的值作为 setter 的参数

c# - asp.net mvc 项目中 NeutralResourcesLanguageAttribute 和 uiCulture 的区别是什么

C#基本属性理解

c# - ASP.NET 中的 session 和线程

mysql - PL-SQL - 我可以将枚举作为函数参数传递吗?

c# - 您在数据应用程序中使用枚举吗?如何使用?