Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums and ComboBoxes in C#

Tags:

c#

enums

combobox

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

like image 596
Boardy Avatar asked Feb 26 '11 19:02

Boardy


People also ask

Can enums hold strings?

No they cannot. They are limited to numeric values of the underlying enum type.

Do enums have to be sequential?

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 .

Can enums have space?

Enum constants are normal Java identifiers, like class or variable names so they can not have spaces in them.

Are enums value types?

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 .


3 Answers

Try this

Months selectedMonth = (Months)Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem.ToString());

instead of

Months selectedMonth = (Months)cboMonthFrom.SelectedItem;

Updated with correct changes

like image 102
SadullahCeran Avatar answered Oct 12 '22 07:10

SadullahCeran


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]);
like image 31
Snowbear Avatar answered Oct 12 '22 09:10

Snowbear


Try

Months selectedMonth = 
    (Months) Enum.Parse(typeof(Months), cboMonthFrom.SelectedItem);
like image 40
SwDevMan81 Avatar answered Oct 12 '22 09:10

SwDevMan81