Enums and ComboBoxes in C#

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

Tags:

C#

Enums

Combobox