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
No they cannot. They are limited to numeric values of the underlying enum type.
It is not necessary to assign sequential values to Enum members. They can have any values. In the above example, we declared an enum PrintMedia .
Enum constants are normal Java identifiers, like class or variable names so they can not have spaces in them.
An enum type is a distinct value type (§8.3) that declares a set of named constants. declares an enum type named Color with members Red , Green , and Blue .
Try this
Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem.ToString());
instead of
Months selectedMonth = (Months)cboMonthFrom.SelectedItem;
Updated with correct changes
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]);
Try
Months selectedMonth =
(Months) Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With