C#麻烦闰年

时间:2015-07-11 14:23:31

标签: c# wpf datetime

我有3个组合框定义为:月,日和年。我设法将所有这些都填写为一个月中的特定日期(3月有31天,2月有28,4月有30,......)。我闰年遇到了麻烦。请参阅下面的代码:

public Form5()
    {
        InitializeComponent();

        DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
        for (int year = 1950; year <= DateTime.Today.Year; year++)
        {
            this.comboBox3.Items.Add(year.ToString());
            if (DateTime.IsLeapYear(year))
            {
                if (comboBox1.Text == "February")
                {
                    {
                        int day;
                        for (day = 0; day < 29; day++)
                        {
                            comboBox2.Items.Add(day.ToString());
                        }
                    }
                }
            }
        }

        for (int i = 1; i <= 12; i++)
        {
            this.comboBox1.Items.Add(info.GetMonthName(i));
        }
    }

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int month = comboBox1.SelectedIndex;
        if (month >= 0)
        {
            month++;
            int days = DateTime.DaysInMonth(DateTime.Today.Date.Year, month);
            var range = Enumerable.Range(1, days);
            comboBox2.DataSource = range.ToList();
        }
    }

有关如何操作的任何建议吗?

1 个答案:

答案 0 :(得分:1)

您只需将当天的加载移至combobox1 selectedindexchanged事件

即可
Source: local data frame [7 x 3]

  ID actual.date match
1  1  1997-10-01     0
2  1  1998-02-01     1
3  2  1999-07-01     0
4  1  2002-05-01     1
5  4  2003-02-03     1
6  3  2005-09-01     1
7  4  2006-05-01     0

在这种情况下,您可以查看年份组合框中的可用信息。然后使用选定的年份作为DateTime.DaysInMonth调用的输入。 (另外不要忘记清除之前组合的数据源,否则你不会看到组合中的任何变化)

最后一个建议:为什么不将这些组合的名称改为更有意义的东西(IE:cboYears,cboMonths,cboDays),你会避免很多混乱

再看一下你的场景,我认为你还需要comboBox3.SelectedINdexChanged中的代码。如果更改年份,您还需要重置日期组合

public void Form5()
{
    InitializeComponent();
    DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
    for (int year = 1950; year <= DateTime.Today.Year; year++)
        this.comboBox3.Items.Add(year.ToString());

    for (int i = 1; i <= 12; i++)
        this.comboBox1.Items.Add(info.GetMonthName(i));
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Sanity check...
    if(string.IsNullOrWhiteSpace(comboBox3.Text))
    {
        MessageBox.Show("Select an year before!");
        return;
    }

    // Get the current selected year and use it in DaysInMonth
    int year = Convert.ToInt32(comboBox3.Text);

    int month = comboBox1.SelectedIndex;
    if (month >= 0)
    {
        combobox2.DataSource = null;

        month++;
        int days = DateTime.DaysInMonth(year, month);
        var range = Enumerable.Range(1, days);
        comboBox2.DataSource = range.ToList();
    }
}