11.WinForm练习--日期选择器

namespace _12日期选择器
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    private void Form1_Load(object sender, EventArgs e)
    {
        //获取当前时间
        int year = DateTime.Now.Year;
        //当程序运行时就将年份加载进去cboYears
        for (int i = year; i >=1949; i--)
        {
            cboYears.Items.Add(i+"年");
        }
    }

    private void cboYears_SelectedIndexChanged(object sender, EventArgs e)
    {
        //添加月份之前清空之前记录
        cboMonths.Items.Clear();
        //当选择年份时,加载月份
        for (int i = 1; i <= 12; i++)
        {
            cboMonths.Items.Add(i+"月");
        }
    }

    private void cboMonths_SelectedIndexChanged(object sender, EventArgs e)
    {
        //定义一个day来存储天数
        int day = 0;
        //加载day之前清空之前记录
        cboDays.Items.Clear();
        //获得月份
        string strmonth = cboMonths.SelectedItem.ToString().Split(new char[] { '月' }, StringSplitOptions.RemoveEmptyEntries)[0];
        //获得年份
        string strYear = cboYears.SelectedItem.ToString().Split(new char[] { '年' }, StringSplitOptions.RemoveEmptyEntries)[0];
        //将年月字符串类型转换成int类型
        int year = Convert.ToInt32(strYear);
        int month = Convert.ToInt32(strmonth);
        //对month进行多条件判断
        switch (month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:day = 31;
                break;
            case 2:if(year%400==0 || year%4==0 && year % 100 != 0)
                {
                    day = 29;
                }
                else
                {
                    day = 28;
                }
                break;
            default:day = 30;
                break;
        }
        for (int i = 1; i <= day; i++)
        {
            cboDays.Items.Add(i+"日");
        }
    }
}

}

猜你喜欢

转载自blog.51cto.com/12679593/2398371
今日推荐