C# 中的枚举和组合框
我目前正在开发一个 C# 应用程序。
我需要使用带有组合框的枚举来获取选定的月份。我有以下内容来创建枚举:
enum Months
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};
然后,我使用以下内容初始化组合框:
cboMonthFrom.Items.AddRange(Enum.GetNames(typeof(Months)));
这段代码工作正常,但问题是当我尝试获取所选月份的所选枚举值时。
为了从 ComboBox 中获取枚举值,我使用了以下方法:
private void cboMonthFrom_SelectedIndexChanged(object sender, EventArgs)
{
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
Console.WriteLine("Selected Month: " + (int)selectedMonth);
}
但是,当我尝试运行上面的代码时,它会出现错误:发生了“System.InvalidCastException”类型的第一次机会异常
。
我做错了什么。
感谢您提供的任何帮助
I am currently developing a C# application.
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
};
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 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);
}
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
.
What I have done wrong.
Thanks for any help you can provide
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试这个
而不是
用正确的更改更新
Try this
instead of
Updated with correct changes
问题是您使用字符串名称填充组合框(
Enum.GetNames
返回string[]
),然后尝试将其转换为枚举。一种可能的解决方案可能是:我还会考虑使用 .Net 中的现有月份信息,而不是添加枚举:
The issue is that you're populating combobox with string names (
Enum.GetNames
returnsstring[]
) and later you try to cast it to your enum. One possible solution could be:I would also consider using existing month information from .Net instead of adding your enum:
尝试
Try
确实没有理由使用
Enum.GetNames
。如果您确实想要月份,为什么要将字符串存储在 ComboBox 中?只需使用
Enum.GetValues
即可:There is really no reason to use
Enum.GetNames
at all. Why store strings in the ComboBox if you actually want the months?Just use
Enum.GetValues
instead:您已将月份名称存储在组合框中,而不是 int 值。您选择的项目将是一个字符串。
You've stored the names of the months in the combobox, not the int values. Your selected item will be a string.
这是我的一行解决方案:
comboBox1.DataSource = Enum.GetValues( typeof( DragDropEffects ) );
这将为您提供所选项目:
DragDropEffectseffects = ( DragDropEffects )comboBox1.SelectedItem;
注意:您可以使用任何您喜欢的枚举,包括您自己的枚举。
Here is my one line solution:
comboBox1.DataSource = Enum.GetValues( typeof( DragDropEffects ) );
This will get you the selected item:
DragDropEffects effects = ( DragDropEffects ) comboBox1.SelectedItem;
Note: You can use any Enum that you like including your own.