问题
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);
}
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
回答1:
Try this
Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem.ToString());
instead of
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
Updated with correct changes
回答2:
The issue is that you're populating combobox with string names (Enum.GetNames returns string[]) and later you try to cast it to your enum. One possible solution could be:
Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem);
I would also consider using existing month information from .Net instead of adding your enum:
var formatInfo = new System.Globalization.DateTimeFormatInfo();
var months = Enumerable.Range(1, 12).Select(n => formatInfo.MonthNames[n]);
回答3:
Try
Months selectedMonth =
(Months) Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem);
回答4:
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:
foreach (var month in Enum.GetValues(typeof(Months)))
cboMonthFrom.Items.Add(month);
[...]
// This works now
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
回答5:
You've stored the names of the months in the combobox, not the int values. Your selected item will be a string.
来源:https://stackoverflow.com/questions/5129378/enums-and-combo-boxes-in-c-sharp