Set DateTimePicker value to be null

前端 未结 8 1098
感情败类
感情败类 2020-12-01 16:43

I am developing a WinForms UI with two DateTimePicker controls. Initially I want to set the value of the controls to null until a user selects a date. If the us

8条回答
  •  死守一世寂寞
    2020-12-01 17:21

    I know this is an older post, but others might still find this useful. It is fairly elegant and concise. I used this with a .Net 4.0 DateTimePicker but earlier versions should work with minimal tweaking. It leverages MinDate and Checked.

        // Use ValueChanged to decide if the value should be displayed:
        dateTimePicker1.ValueChanged += (s, e) => { dateTimePicker1.CustomFormat = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? "MM/dd/yyyy" : " "; };
    
        //When getting the value back out, use something like the following:
        DateTime? dt = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ?  (DateTime?) dateTimePicker1.Value : null; 
        // or
        DateTime dt2 = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ?  dateTimePicker1.Value : DateTime.MinValue; 
    

提交回复
热议问题