ComboBox 日期選擇器(年月日)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
private void Form1_Load(object sender, EventArgs e)
{
//程式載入時,將年份加入下拉框中
int year = DateTime.Now.Year; //當前年份
for (int i = year; i >= 1949; i--) {
cboYear.Items.Add($"{i}年");
}
}
/// <summary>
/// 當年份發生改變的時候,加載月份
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
{
//添加之前要先清空之前的內容
cboMonth.Items.Clear();
for (int i = 1; i <= 12; i++) {
cboMonth.Items.Add($"{i}月");
}
}
/// <summary>
/// 當月份發生變化時,添加天
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
{
//添加之前要先清空之前的內容
cboDay.Items.Clear();
//宣告一個變數來儲存天數
int day = 0;
//取得月份,年份
string strMonth = cboMonth.SelectedItem.ToString()!.Split(new char[] { '月' }, StringSplitOptions.RemoveEmptyEntries)[0];
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++) {
cboDay.Items.Add($"{i}天");
}
}
閏月 & 平月
1
2
3
4
5
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
day = 29; //閏月
} else {
day = 28; //平月
}