Winform-NumericUpDown和ComboBox年月日时联动

由于项目中需要。断断续续浪费了几天时间做出来了。之前写好了一个但是由于逻辑不怎么对。又重新写了一个。基本的处理都弄好了。闰年闰月的变动。例如2016029的状态在点击到2017年时显示的时2017028,例如3月31选择2月时就变成2.1号等等逻辑处理,有什么不对的大家多多指点。上图上代码:

 

 

变更前:                                                                                                                     变更后:

变更前:                                                                                                               变更后:

代码:

#region コンポーネント デザイナーで生成されたコード

		///  
		/// デザイナー サポートに必要なメソッドです。このメソッドの内容を 
		/// コード エディターで変更しないでください。
		/// 
		private void InitializeComponent()
		{
			this.monthCalendar = new System.Windows.Forms.MonthCalendar();
			this.nUpDownYear = new System.Windows.Forms.NumericUpDown();
			this.label11 = new System.Windows.Forms.Label();
			this.label10 = new System.Windows.Forms.Label();
			this.label9 = new System.Windows.Forms.Label();
			this.comBoxDay = new System.Windows.Forms.ComboBox();
			this.comBoxHour = new System.Windows.Forms.ComboBox();
			this.comBoxMonth = new System.Windows.Forms.ComboBox();
			this.label8 = new System.Windows.Forms.Label();
			((System.ComponentModel.ISupportInitialize)(this.nUpDownYear)).BeginInit();
			this.SuspendLayout();
			// 
			// monthCalendar
			// 
			this.monthCalendar.Location = new System.Drawing.Point(17, 27);
			this.monthCalendar.MaxDate = new System.DateTime(2030, 12, 31, 23, 59, 0, 0);
			this.monthCalendar.MinDate = new System.DateTime(2013, 1, 1, 0, 0, 0, 0);
			this.monthCalendar.Name = "monthCalendar";
			this.monthCalendar.ShowTodayCircle = false;
			this.monthCalendar.TabIndex = 55;
			this.monthCalendar.DateSelected += new System.Windows.Forms.DateRangeEventHandler(this.monthCalendar_DateSelected);
			// 
			// nUpDownYear
			// 
			this.nUpDownYear.Location = new System.Drawing.Point(2, 2);
			this.nUpDownYear.Maximum = new decimal(new int[] {
            2030,
            0,
            0,
            0});
			this.nUpDownYear.Minimum = new decimal(new int[] {
            2013,
            0,
            0,
            0});
			this.nUpDownYear.Name = "nUpDownYear";
			this.nUpDownYear.ReadOnly = true;
			this.nUpDownYear.Size = new System.Drawing.Size(51, 19);
			this.nUpDownYear.TabIndex = 51;
			this.nUpDownYear.Value = new decimal(new int[] {
            2013,
            0,
            0,
            0});
			this.nUpDownYear.ValueChanged += new System.EventHandler(this.nUpDownYear_ValueChanged);
			// 
			// label11
			// 
			this.label11.AutoSize = true;
			this.label11.Location = new System.Drawing.Point(244, 6);
			this.label11.Name = "label11";
			this.label11.Size = new System.Drawing.Size(17, 12);
			this.label11.TabIndex = 59;
			this.label11.Text = "時";
			// 
			// label10
			// 
			this.label10.AutoSize = true;
			this.label10.Location = new System.Drawing.Point(182, 5);
			this.label10.Name = "label10";
			this.label10.Size = new System.Drawing.Size(17, 12);
			this.label10.TabIndex = 58;
			this.label10.Text = "日";
			// 
			// label9
			// 
			this.label9.AutoSize = true;
			this.label9.Location = new System.Drawing.Point(119, 5);
			this.label9.Name = "label9";
			this.label9.Size = new System.Drawing.Size(17, 12);
			this.label9.TabIndex = 57;
			this.label9.Text = "月";
			// 
			// comBoxDay
			// 
			this.comBoxDay.DropDownHeight = 375;
			this.comBoxDay.DropDownWidth = 20;
			this.comBoxDay.FormattingEnabled = true;
			this.comBoxDay.IntegralHeight = false;
			this.comBoxDay.Location = new System.Drawing.Point(142, 2);
			this.comBoxDay.Name = "comBoxDay";
			this.comBoxDay.Size = new System.Drawing.Size(38, 20);
			this.comBoxDay.TabIndex = 53;
			this.comBoxDay.SelectedIndexChanged += new System.EventHandler(this.comBoxDay_SelectedIndexChanged);
			// 
			// comBoxHour
			// 
			this.comBoxHour.FormattingEnabled = true;
			this.comBoxHour.Items.AddRange(new object[] {
            "01",
            "02",
            "03",
            "04",
            "05",
            "06",
            "07",
            "08",
            "09",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "17",
            "18",
            "19",
            "20",
            "21",
            "22",
            "23",
            "24"});
			this.comBoxHour.Location = new System.Drawing.Point(202, 2);
			this.comBoxHour.Name = "comBoxHour";
			this.comBoxHour.Size = new System.Drawing.Size(38, 20);
			this.comBoxHour.TabIndex = 54;
			this.comBoxHour.SelectedIndexChanged += new System.EventHandler(this.comBoxHour_SelectedIndexChanged);
			// 
			// comBoxMonth
			// 
			this.comBoxMonth.FormattingEnabled = true;
			this.comBoxMonth.Items.AddRange(new object[] {
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "11",
            "12"});
			this.comBoxMonth.Location = new System.Drawing.Point(79, 2);
			this.comBoxMonth.Name = "comBoxMonth";
			this.comBoxMonth.Size = new System.Drawing.Size(38, 20);
			this.comBoxMonth.TabIndex = 52;
			this.comBoxMonth.SelectedIndexChanged += new System.EventHandler(this.comBoxMonth_SelectedIndexChanged);
			// 
			// label8
			// 
			this.label8.AutoSize = true;
			this.label8.Location = new System.Drawing.Point(56, 5);
			this.label8.Name = "label8";
			this.label8.Size = new System.Drawing.Size(17, 12);
			this.label8.TabIndex = 56;
			this.label8.Text = "年";
			// 
			// UcMonthCalendar
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.Controls.Add(this.monthCalendar);
			this.Controls.Add(this.nUpDownYear);
			this.Controls.Add(this.label11);
			this.Controls.Add(this.label10);
			this.Controls.Add(this.label9);
			this.Controls.Add(this.comBoxDay);
			this.Controls.Add(this.comBoxHour);
			this.Controls.Add(this.comBoxMonth);
			this.Controls.Add(this.label8);
			this.Name = "UcMonthCalendar";
			this.Size = new System.Drawing.Size(261, 195);
			this.Load += new System.EventHandler(this.UcMonthCalendar_Load);
			((System.ComponentModel.ISupportInitialize)(this.nUpDownYear)).EndInit();
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		public System.Windows.Forms.MonthCalendar monthCalendar;
		private System.Windows.Forms.NumericUpDown nUpDownYear;
		private System.Windows.Forms.Label label11;
		private System.Windows.Forms.Label label10;
		private System.Windows.Forms.Label label9;
		public System.Windows.Forms.ComboBox comBoxDay;
		public System.Windows.Forms.ComboBox comBoxHour;
		public System.Windows.Forms.ComboBox comBoxMonth;
		private System.Windows.Forms.Label label8;


后台代码:

public partial class UcMonthCalendar : UserControl { public UcMonthCalendar() { InitializeComponent(); } /// /// YearMonthDayHour /// public string YearMonthDayHour { get; set; } private DateTime tnow = DateTime.Now; //既定の28日 string[] sDay = { "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"}; //30ヶ月までの日数 string[] sMonthThirty = { "4", "6", "9", "11" }; //31ヶ月までの日数 string[] sMonthThirty_First = { "1", "3", "5", "7", "8", "10", "12" }; /// /// 日の選択数を維持するように変更する日の選択した数、年を保存 /// string sSlectDay = string.Empty; /// /// (閏年)を表示している状態 /// bool bLeapyear = false; /// /// (閏年)変更の29日を選択 /// string sLeapYear = string.Empty; private void UcMonthCalendar_Load(object sender, EventArgs e) { comBoxDay.SelectedIndexChanged -= new EventHandler(comBoxDay_SelectedIndexChanged); comBoxMonth.SelectedIndexChanged -= new EventHandler(comBoxMonth_SelectedIndexChanged); comBoxHour.SelectedIndexChanged -= new EventHandler(comBoxHour_SelectedIndexChanged); comBoxHour.Text = tnow.Hour.ToString().PadLeft(2,'0'); comBoxMonth.Text = tnow.Month.ToString(); comBoxYear.Text = tnow.Year.ToString(); BindShowDay(tnow.Year.ToString(), tnow.Month.ToString()); comBoxDay.SelectedIndexChanged += new EventHandler(comBoxDay_SelectedIndexChanged); comBoxMonth.SelectedIndexChanged += new EventHandler(comBoxMonth_SelectedIndexChanged); comBoxHour.SelectedIndexChanged += new EventHandler(comBoxHour_SelectedIndexChanged); monthCalendar.Select(); YearMonthDayHour = comBoxYear.Text + comBoxMonth.Text.PadLeft(2, '0') + comBoxDay.Text.PadLeft(2, '0') + comBoxHour.Text.PadLeft(2, '0'); ; //本月の土曜日と日曜日は太字表示する。 monthCalendar.BoldedDates = ComUtil.GetDayOfWeekend(monthCalendar.SelectionStart.ToString("yyyyMM")); //SelectYearMonthDayHour(); } /// /// 変更の日を選択 /// public void BindShowDay(string sYear, string sMonth) { DataTable tblDatas = new DataTable("MonthDay"); DataColumn dc = null; dc = tblDatas.Columns.Add("Day", Type.GetType("System.String")); DataRow newRow; for (int i = 0; i < sDay.Length; i++) { tblDatas.Rows.Add(sDay[i]); } //(閏年)を表示している状態 if ((Convert.ToInt32(sYear) % 4 == 0 && Convert.ToInt32(sYear) % 100 != 0) || Convert.ToInt32(sYear) % 400 == 0) { if (comBoxMonth.Text == "2") { bLeapyear = true; newRow = tblDatas.NewRow(); newRow["Day"] = "29"; tblDatas.Rows.InsertAt(newRow, 28); } } else { bLeapyear = false; } //判断包含30天的月 if (sMonthThirty.Contains(sMonth)) { newRow = tblDatas.NewRow(); newRow["Day"] = "29"; tblDatas.Rows.InsertAt(newRow, 28); newRow = tblDatas.NewRow(); newRow["Day"] = "30"; tblDatas.Rows.InsertAt(newRow, 29); } //判断包含31天的月 if (sMonthThirty_First.Contains(sMonth)) { newRow = tblDatas.NewRow(); newRow["Day"] = "29"; tblDatas.Rows.InsertAt(newRow, 28); newRow = tblDatas.NewRow(); newRow["Day"] = "30"; tblDatas.Rows.InsertAt(newRow, 29); newRow = tblDatas.NewRow(); newRow["Day"] = "31"; tblDatas.Rows.InsertAt(newRow, 30); } comBoxDay.DisplayMember = "Day"; comBoxDay.DataSource = tblDatas; if (!string.IsNullOrEmpty(sSlectDay)) { comBoxDay.Text = sSlectDay; return; } else { comBoxDay.Text = tnow.Day.ToString(); return; } } /// /// 取得変更后的DateTime /// public void ChangeDateTime() { string sTime = string.Empty; sTime = comBoxYear.Text + comBoxMonth.Text.PadLeft(2, '0'); //(閏年)を表示している状態 if (bLeapyear) { if (comBoxMonth.Text == "2") { //2月になったら、選択した日付の日は閏の月の日数より大きくの場合 if (int.Parse(sSlectDay) > 29) { sSlectDay = "1"; comBoxDay.Text = sSlectDay; } //2月になったら、選択した日付の日は閏の月の日数より小さくの場合 else if (int.Parse(sSlectDay) < 29) { comBoxDay.Text = sSlectDay; } //上記以外の場合 else { sSlectDay = "29"; comBoxDay.Text = sSlectDay; } } } else { //閏年ではなくで、2月の場合 if (comBoxMonth.Text == "2") { if (sLeapYear == "29") { sSlectDay = "28"; comBoxDay.Text = sSlectDay; sLeapYear = ""; } else if (int.Parse(sSlectDay) > 28) { sSlectDay = "1"; comBoxDay.Text = sSlectDay; } else comBoxDay.Text = sSlectDay; } } //毎月30日の場合 if (sMonthThirty.Contains(comBoxMonth.Text)) { if (int.Parse(sSlectDay) > 30) { sSlectDay = "1"; comBoxDay.Text = sSlectDay; } } //当日は空です if (!string.IsNullOrEmpty(sSlectDay)) { sTime = sTime + sSlectDay.PadLeft(2, '0'); } else { if (string.IsNullOrEmpty(comBoxDay.Text)) return; //日数を選択し、及び維持するために維持する sTime = sTime + comBoxDay.Text.PadLeft(2, '0'); } //} DateTime dt = DateTime.ParseExact(sTime, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); monthCalendar.SetDate(dt); monthCalendar.Select(); YearMonthDayHour = sTime + comBoxHour.Text.PadLeft(2, '0');  //本月の土曜日と日曜日は太字表示する。 monthCalendar.BoldedDates = ComUtil.GetDayOfWeekend(monthCalendar.SelectionStart.ToString("yyyyMM")); //SelectYearMonthDayHour(); } /// /// 選択月の状態に応じて実施するか否かをその日の選択 /// bool bSelectstate = false; /// /// 年の値の変更を選択してください /// private void nUpDownYear_ValueChanged(object sender, EventArgs e) { sSlectDay = comBoxDay.Text; sLeapYear = sSlectDay; bSelectstate = true; BindShowDay(comBoxYear.Text.ToString(), comBoxMonth.Text.ToString()); ChangeDateTime(); bSelectstate = false; } /// /// 月:コンボボックスの値の変更を選択してください /// private void comBoxMonth_SelectedIndexChanged(object sender, EventArgs e) { sSlectDay = comBoxDay.Text; bSelectstate = true; BindShowDay(comBoxYear.Text.ToString(), comBoxMonth.Text.ToString()); ChangeDateTime(); bSelectstate = false; comBoxMonth.Focus(); } /// /// 日:コンボボックスの値の変更を選択してください /// private void comBoxDay_SelectedIndexChanged(object sender, EventArgs e) { if (bSelectstate == false) { sSlectDay = comBoxDay.Text; ChangeDateTime(); } comBoxDay.Focus(); } private void comBoxHour_SelectedIndexChanged(object sender, EventArgs e) { YearMonthDayHour = comBoxYear.Text + comBoxMonth.Text.PadLeft(2, '0') + comBoxDay.Text.PadLeft(2, '0') + comBoxHour.Text.PadLeft(2, '0'); ; } /// /// MonthCalendarコントロールの変更で選択した日付が発生する。 /// private void monthCalendar_DateSelected(object sender, DateRangeEventArgs e) { 本月の土曜日と日曜日は太字表示する。 //monthCalendar.BoldedDates = ComUtil.GetDayOfWeekend(monthCalendar.SelectionStart.ToString("yyyyMM")); //comBoxYear.Text = e.Start.Year.ToString(); //comBoxMonth.Text = e.Start.Month.ToString(); //comBoxDay.Text = e.Start.Day.ToString(); //monthCalendar.Focus(); } /// /// //特殊キー(スペースを含む)、および処理されません /// private void comBoxMonthDayHour_KeyPress(object sender, KeyPressEventArgs e) { if ((int)e.KeyChar < 32) { e.Handled = true; return; } e.Handled = true; return; } /// /// delete,Backキーを無効にする /// private void comBoxMonthDayHour_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back) { e.Handled = true; return; } } /// /// 本月の土曜日と日曜日は太字表示する。 /// private void monthCalendar_MouseDown(object sender, MouseEventArgs e) { MonthCalendar tmp = (MonthCalendar)sender; MonthCalendar.HitTestInfo hitInfo = monthCalendar.HitTest(e.Location); string sNextMonthDay = tmp.SelectionStart.Year + tmp.SelectionStart.Month.ToString().PadLeft(2, '0') +YearMonthDayHour.Substring(6,2).PadLeft(2, '0'); DateTime dt = DateTime.ParseExact(sNextMonthDay, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); if (hitInfo.HitArea == MonthCalendar.HitArea.PrevMonthButton  || hitInfo.HitArea==MonthCalendar.HitArea.NextMonthButton ||hitInfo.HitArea == MonthCalendar.HitArea.Date) { //本月の土曜日と日曜日は太字表示する。 monthCalendar.BoldedDates = ComUtil.GetDayOfWeekend(sNextMonthDay.Substring(0, 6)); comBoxYear.Text = tmp.SelectionStart.Year.ToString(); comBoxMonth.Text = tmp.SelectionStart.Month.ToString(); comBoxDay.Text = tmp.SelectionStart.Day.ToString(); monthCalendar.SetDate(dt); monthCalendar.Focus(); } } } }

ps:其实还是不完善。

另外一版代码。主要注释的代码是判断选择24时后进行判断年月日 变化的。 例如1.31 24时则变化为2.1 00

/// 
		/// 取得変更后的DateTime
		/// 
		public void ChangeDateTime()
		{
			string sTime = string.Empty;

			sTime = nUpDownYear.Value+ comBoxMonth.Text.PadLeft(2, '0');
			//2013/0312 begin
			//時指定変更
			//if (comBoxHour.Text == "24")
			//{
			//	//開始日時の年+1
			//	if (comBoxMonth.Text.PadLeft(2, '0') + comBoxDay.Text.PadLeft(2, '0') == "1231")
			//	{
			//		if (!string.IsNullOrEmpty(nUpDownYear.Value.ToString()))
			//		{
			//			sTime = nUpDownYear.Value + 1 + "010100";
			//			//comBoxMonth.Text = "1";
			//			//comBoxDay.Text = "1";
			//			//sSlectDay = "1";
			//			//nUpDownYear.Value = nUpDownYear.Value + 1;
			//			//return;
			//		}

			//	}
			//	//変更した月の1日が表示される
			//	else if (comBoxDay.Text.PadLeft(2, '0') == "31")
			//	{
			//		sTime = nUpDownYear.Value + Convert.ToString(int.Parse(comBoxMonth.Text) + 1).PadLeft(2, '0') + "0100";
			//		//sSlectDay = "1";
			//		//comBoxMonth.Text = Convert.ToString(int.Parse(comBoxMonth.Text) + 1);
			//	}
			//	//開始日時の日+1
			//	else
			//	{
			//		sTime = sTime + Convert.ToString(int.Parse(comBoxDay.Text) + 1).PadLeft(2, '0') + "00";
			//		comBoxDay.Text = Convert.ToString(int.Parse(comBoxDay.Text) + 1);
			//	}
			//}
			//else
			//{
			//20130312 end
				//(閏年)を表示している状態
				if (bLeapyear)
				{
					if (comBoxMonth.Text == "2")
					{
						//2月になったら、選択した日付の日は閏の月の日数より大きくの場合
						if (int.Parse(sSlectDay) > 29)
						{
							sSlectDay = "1";
							comBoxDay.Text = sSlectDay;
						}
						//2月になったら、選択した日付の日は閏の月の日数より小さくの場合
						else if (int.Parse(sSlectDay) < 29)
						{
							comBoxDay.Text = sSlectDay;
						}
						//上記以外の場合
						else
						{
							sSlectDay = "29";
							comBoxDay.Text = sSlectDay;
						}
					}
				}
				else
				{
					//閏年ではなくで、2月の場合
					if (comBoxMonth.Text == "2")
					{
						if (sLeapYear == "29")
						{
							sSlectDay = "28";
							comBoxDay.Text = sSlectDay;
							sLeapYear = "";
						}
						else if (int.Parse(sSlectDay) > 28)
						{
							sSlectDay = "1";
							comBoxDay.Text = sSlectDay;
						}
						else
							comBoxDay.Text = sSlectDay;
					}
				}
				//毎月30日の場合
				if (sMonthThirty.Contains(comBoxMonth.Text))
				{
					if (int.Parse(sSlectDay) > 30)
					{
						sSlectDay = "1";
						comBoxDay.Text = sSlectDay;
					}
				}
			//20130312 begin
				当日は空です
				//if (!string.IsNullOrEmpty(sSlectDay))
				//{
				//	sTime = sTime + sSlectDay.PadLeft(2, '0') + comBoxHour.Text.PadLeft(2, '0');
				//}
				//else
				//{
				//	if (string.IsNullOrEmpty(comBoxDay.Text)) return;
				//	//日数を選択し、及び維持するために維持する
				//	sTime = sTime + comBoxDay.Text.PadLeft(2, '0') + comBoxHour.Text.PadLeft(2, '0');
				//}
			//20130312 end
				//当日は空です
				if (!string.IsNullOrEmpty(sSlectDay))
				{
					sTime = sTime + sSlectDay.PadLeft(2, '0');
				}
				else
				{
					if (string.IsNullOrEmpty(comBoxDay.Text)) return;
					//日数を選択し、及び維持するために維持する
					sTime = sTime + comBoxDay.Text.PadLeft(2, '0');
				}
			//}
			DateTime dt = DateTime.ParseExact(sTime, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
			monthCalendar.SetDate(dt);
			monthCalendar.Select();
		}


 

 

你可能感兴趣的:(.NET,And,C#,WinForm学习,Winform,NumericUpDown,ComboBox,年月日)