Boardy
Boardy

Reputation: 36205

Enums and ComboBoxes in C#

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

Upvotes: 7

Views: 13733

Answers (6)

TymerTopCat
TymerTopCat

Reputation: 11

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.

Upvotes: 0

Timwi
Timwi

Reputation: 66573

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;

Upvotes: 3

SwDevMan81
SwDevMan81

Reputation: 49978

Try

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

Upvotes: 5

Bryn Keller
Bryn Keller

Reputation: 989

You've stored the names of the months in the combobox, not the int values. Your selected item will be a string.

Upvotes: 1

Snowbear
Snowbear

Reputation: 17274

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]);

Upvotes: 6

SadullahCeran
SadullahCeran

Reputation: 2435

Try this

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

instead of

Months selectedMonth = (Months)cboMonthFrom.SelectedItem;

Updated with correct changes

Upvotes: 7

Related Questions