toolStrip1 增加两个日期型控件并使之联动




在 toolStrip 中增加DateTimePicker 控件,并解决两个日期型控件联动问题

      DateTimePicker dtpStart, dtpEnd; //两个日期控件

      private void initializeControls()
      {
         try
         {
            #region 增加 日期


            dtpStart = new DateTimePicker();
            //dtpStart.Format = DateTimePickerFormat.Custom;//自动设置
            //dtpStart.CustomFormat = "MM月dd日";//自定义格式 
            dtpStart.Format = DateTimePickerFormat.Short;
            dtpStart.Width = 120;
            dtpStart.Value = DateTime.Now;
            dtpStart.ShowCheckBox = true;
           // Controls.Add(dtpStart);
            ToolStripControlHost dateStartItem = new ToolStripControlHost(dtpStart);
            this.toolStrip1.Items.Insert(1, dateStartItem);

            dtpEnd = new DateTimePicker();
            //dtpEnd.Format = DateTimePickerFormat.Custom;//自动设置
            //dtpEnd.CustomFormat = "MM月dd日";//自定义格式 
            dtpEnd.Format = DateTimePickerFormat.Short;
            dtpEnd.Width = 120;
            dtpEnd.Value = DateTime.Now;
            dtpEnd.ShowCheckBox = true;
            //Controls.Add(dtpEnd);
            ToolStripControlHost dateEndItem = new ToolStripControlHost(dtpEnd);
            this.toolStrip1.Items.Insert(3, dateEndItem);

            dtpEnd.Enabled = false; //使之不能使用,以便控件两个控件联动.
            dtpStart.Checked = false;
            dtpEnd.Checked = false;
            #endregion

            //先注册声明一个事件绑定:
            dtpStart.Leave += new EventHandler(dtpStart_Leave);
            dtpStart.MouseLeave += new EventHandler(dtpStart_Leave);



    

         }
         catch (Exception exc)
         {
            MessageBox.Show(exc.Message, "异常信息 initializeControls ", MessageBoxButtons.OK, MessageBoxIcon.Error);

         }
      }

      private void dtpStart_Leave(object sender, EventArgs e)
      {
         try
         {
            if (dtpStart.Checked )
            {
               dtpEnd.Checked = true;
               dtpStart.Checked = true;
               dtpEnd.Enabled = true;
            }
            else if( !dtpStart.Checked  )
            {
               dtpEnd.Checked = false;
               dtpStart.Checked = false;
               dtpEnd.Enabled = false;
            }
            toolTip1.SetToolTip(this.dtpStart, "日期只能都选或者都不选");
         }
         catch (Exception exc)
         {
            MessageBox.Show(exc.Message, "异常信息 dtpStart_MouseEnter ", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }

      }


你可能感兴趣的:(C#,控件)