这应该可以工作(假设您的组合框所在的表单名为“mainForm”,组合框名为“comboBoxMonth”和“comboBoxYear”):
private void mainForm_Shown(object sender, EventArgs e)
{
PopulateMonthsAndYears();
}
private void PopulateMonthsAndYears()
{
const int DECEMBER = 11;
const int BEGIN_YEAR = 1983; // KCMS
comboBoxMonth.Items.AddRange(PlatypusConstsAndUtils.MonthsFull.ToArray<object>());
comboBoxMonth.SelectedIndex = PlatypusConstsAndUtils.GetIndexForPreviousMonth();
comboBoxYear.DataSource = Enumerable.Range(BEGIN_YEAR, DateTime.Now.Year - BEGIN_YEAR + 1).ToList();
comboBoxYear.SelectedIndex = comboBoxYear.Items.IndexOf(DateTime.Now.Year);
// However, if it is January (and thus the month is set to December), set the year to previous also
if (comboBoxMonth.SelectedIndex == DECEMBER)
{
comboBoxYear.SelectedIndex = comboBoxYear.Items.IndexOf(DateTime.Now.Year - 1);
}
}
...以及保存月份 vals 的类(当然,您可以将字符串 vals 更改为西班牙语或德语或克林贡语或任何“漂浮在您的船上”):
public static class PlatypusConstsAndUtils
{
public static List<string> MonthsFull = new List<string>
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
public static int GetIndexForPreviousMonth()
{
// Months are 1-based, but return the index, which is 0-based, so decrement it
const int JANUARY = 1;
const int DECEMBER = 12;
int prevMonth;
int currentMonth = DateTime.Now.Month;
if (currentMonth == JANUARY)
{
prevMonth = DECEMBER - 1;
}
else
{
prevMonth = DateTime.Now.Month - 2;
}
return prevMonth;
}
. . .