c# winform时间控件dateTimePicker增加清空日期功能

  • Post author:
  • Post category:其他


显示时间控件的复选框,当复选框取消勾选时,显示时间。当复选框取消勾选时,不显示时间

在这里插入图片描述

this.dateTimePicker1.CustomFormat = "yyyy-MM-dd";
this.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom;

this.dateTimePicker1.ShowCheckBox = true;
this.dateTimePicker1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dateTimePicker1_MouseDown);

private void dateTimePicker1_MouseDown(object sender, MouseEventArgs e)
        {
            if (!this.dateTimePicker1.Checked)//微软时间控件复选框不勾选时,时间显示为空
            {
                this.dateTimePicker1.Format = DateTimePickerFormat.Custom;
                this.dateTimePicker1.CustomFormat = "   ";
                this.dateTimePicker1.Text = "";
            }
            else
            {
                this.dateTimePicker1.Format = DateTimePickerFormat.Custom;
                this.dateTimePicker1.CustomFormat = "yyyy-MM-dd";
                if (string.IsNullOrEmpty(this.dateTimePicker1.Text))
                {
                    this.dateTimePicker1.Text = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }
        }