设置datetimepicker的默认值(如果相等),设置为0

时间:2017-08-17 20:27:29

标签: c# .net

如果该值等于默认日期'现在'我试图将datetimepicker设置为0。这就是我所拥有的,但即使更改了值,它也始终返回null。

private string _BirthDate;

public Form1()
{
    InitializeComponent();
    dateTimePicker1.MaxDate = DateTime.Now; // Ensures no future dates are set.
    dateTimePicker1.Format = DateTimePickerFormat.Custom;
    //dateTimePicker1.Checked = true;
    dateTimePicker1.CustomFormat = dateTimePicker1.CustomFormat;
    dateTimePicker1.Value = DateTime.Now;
}

public string BirthDate
{
    set
    {
        if (dateTimePicker1.Value.Date != DateTime.Now)
        {
            _BirthDate = value;
        }
    }
    get { return _BirthDate; }
}

private void button1_Click(object sender, EventArgs e)
{
    string date = Convert.ToString(BirthDate); 
}

我知道DateTime类不能使用,但为了解决这个问题,我只想检查该值是否为默认值,如果是,则将其设置为0。

2 个答案:

答案 0 :(得分:0)

您可以使DateTime可以为空

DateTime? date = null;

答案 1 :(得分:0)

所有解决的问题现在只需要调整。正如你们所说的那样,我没有设置值或属性,所以无论如何它都会为null

private string _BirthDate;

        public Form1()
        {
            InitializeComponent();
            dateTimePicker1.MaxDate = DateTime.Now; // Ensures no future dates are set.
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            //dateTimePicker1.Checked = true;
            dateTimePicker1.CustomFormat = dateTimePicker1.CustomFormat;
            dateTimePicker1.Value = DateTime.Now;
        }
        public string BirthDate
        {
            set
            {
                if (dateTimePicker1.Value.Date == DateTime.Today)
                {
                    dateTimePicker1.CustomFormat = " ";

                }
                else
                {
                    _BirthDate = value;
                }
            }
            get { return _BirthDate; }
        }


        private void button1_Click(object sender, EventArgs e)
        {

           BirthDate = dateTimePicker1.Value.ToString();
        }