简体   繁体   中英

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

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

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;

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM