using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 日期联动下拉框
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
BindYear();
BindMonth();
BindDay();
}
private void BindYear()
{
int CurrentYear = DateTime.Now.Year;
int StartYear = CurrentYear - 10;
int EndYear = CurrentYear + 10;
comboBoxYear.Text = "请选择年份";
for (int year = StartYear; year <= EndYear; year++)
comboBoxYear.Items.Add(year.ToString());
}
private void BindMonth()
{
comboBoxMonth.Text = "请选择月份";
for (int month = 1; month <= 12; month++)
comboBoxMonth.Items.Add(month.ToString());
}
private void BindDay()
{
comboBoxDay.Text = "请选择天";
if (comboBoxYear.SelectedIndex >= 0 && comboBoxMonth.SelectedIndex >= 0)
{
//获取某年某月中的天数,自动考虑是否闰年的问题
int DaysOfTheMonth = DateTime.DaysInMonth(int.Parse(comboBoxYear.Text ), int.Parse(comboBoxMonth.Text));
for (int day = 1; day <= DaysOfTheMonth; day++)
comboBoxDay.Items.Add(day.ToString());
}
}
private void comboBoxYear_SelectedIndexChanged(object sender, EventArgs e)
{
BindDay();
}
private void comboBoxMonth_SelectedIndexChanged(object sender, EventArgs e)
{
BindDay();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBoxYear.SelectedIndex >= 0 && comboBoxMonth.SelectedIndex >= 0 && comboBoxDay.SelectedIndex >= 0)
{
string year = comboBoxYear.Text;
string month = comboBoxMonth.Text;
string day = comboBoxDay.Text;
string str = year + "年" + month + "月" + day + "日";
MessageBox.Show(str);
}
}
}
}