c#ComboBox控件日期选择器

c#ComboBox控件日期选择器_第1张图片

 

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //当程序加载的时候将年份添加到下拉框中
            //获得当前年份
            int year = DateTime.Now.Year;
            for (int i = year; i >= 1949; i--)
            {
                //添加年份列表集合
                cboYear.Items.Add(i + "年");
            }
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            //清除当前月份列表集合
            cboMonth.Items.Clear();
            for (int i = 1; i <=12; i++)
            {
                //添加月份列表集合
                cboMonth.Items.Add(i + "月");
            }

        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            //清除天数列表集合
            cboDays.Items.Clear();
            int day = 0;
            //将列表中选中的月份去除月字后赋值给strMonth
            string strMonth = cboMonth.SelectedItem.ToString().Split(new char[] { '月' },StringSplitOptions.RemoveEmptyEntries)[0];
            //将列表中选中的年份去除年字后赋值给strYear
            string strYear = cboYear.SelectedItem.ToString().Split(new char[] { '年' }, StringSplitOptions.RemoveEmptyEntries)[0];

            int year = Convert.ToInt32(strYear);
            int month = Convert.ToInt32(strMonth);
            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 + "日");
            }

        }
    }

你可能感兴趣的:(c#)