Enums and Combo Boxes in C #

I am currently developing a C # application.

I need to use an enumeration with a combo box to get the selected month. I have the following to create an enumeration:

enum Months { January = 1, February, March, April, May, June, July, August, September, October, November, December }; 

Then I initialize the combo box using the following:

 cboMonthFrom.Items.AddRange(Enum.GetNames(typeof(Months))); 

This bit of code works fine, however the problem is that I am trying to get the selected enumeration value for the selected month

To get the value of an enumerator from a combo box, I 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 above code, I get the error "The first random exception of type System.InvalidCastException .

What I did wrong.

Thanks for any help you can provide.

+7
source share
5 answers

try it

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

instead

 Months selectedMonth = (Months)cboMonthFrom.SelectedItem; 

Updated with correct changes.

+7
source

The problem is that you populate combobox with string names ( Enum.GetNames returns string[] ) and then you try to pass it to your list. One possible solution could be:

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

I will also consider using existing month information from .Net instead of adding your enumeration:

 var formatInfo = new System.Globalization.DateTimeFormatInfo(); var months = Enumerable.Range(1, 12).Select(n => formatInfo.MonthNames[n]); 
+6
source

Try

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

There really is no reason to use Enum.GetNames at all. Why store strings in a ComboBox if you really want 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; 
+3
source

You saved month names in combobox, not int values. Your selected item will be a string.

+1
source

All Articles