Search code examples
c#.netwinformsdatecombobox

How can I populate a "Months" combobox and a "Years" combobox from a supplied year, and have their values default to the last month?


I need to let the user select a month and a year. Usually, they will want the last month (e.g., if it's December 18th, 2015, they will normally want to select November 2015). So I want those values to be the ones pre-selected in the comboboxes.

How can I do this (in C#) and also have it be "December 2015" once crossing the Rubicon (Euphrates?) to January 2016?

I also want it to not add 2016 until it is 2016 (and so on, as the years go by) and start from a predetermined year (not year 0 or 1970 or anything like that, necessarily).


Solution

  • You can use DateTimeFormatInfo.MonthNames to find month names for a culture. Some cultures have 13 months, so DateTimeFormat.MonthNames returns an array with 13 month.

    But since it seems you want to use Gregorian calendar, you only need to use 12 month names and I used InvariantCulture to get month names.

    You can use such code:

    monthComboBox.DataSource = CultureInfo.InvariantCulture.DateTimeFormat
                                                         .MonthNames.Take(12).ToList();
    monthComboBox.SelectedItem = CultureInfo.InvariantCulture.DateTimeFormat
                                            .MonthNames[DateTime.Now.AddMonths(-1).Month - 1];
    
    yearComboBox.DataSource = Enumerable.Range(1983, DateTime.Now.Year - 1983 + 1).ToList();
    yearComboBox.SelectedItem = DateTime.Now.Year;
    

    You can use CurrentCulture or some other culture you prefer.