how to set datetimepicker with null value if date not selected(c# winforms)

后端 未结 6 1024
夕颜
夕颜 2020-12-14 03:21
Binding b = new Binding( \"Value\", person, \"BdayNullable\", true );
dtBirthdayNullable.DataBindings.Add( b );
b.Format += new ConvertEventHandler( dtBirthdayNullab         


        
6条回答
  •  遥遥无期
    2020-12-14 04:02

    I like the ShowCheckBox option. I would take it one step further and encapsulate it with two extension methods to avoid duplication and have cleaner looking code:

    public static DateTime? NullableValue(this DateTimePicker dtp)
    {
        return dtp.Checked ? dtp.Value : (DateTime?)null;
    }
    
    public static void NullableValue(this DateTimePicker dtp, DateTime? value)
    {
        dtp.Checked = value.HasValue;
        if (value.HasValue) dtp.Value = value.Value;
    }
    

    Then, the get and set code looks like:

    dtpSafetyApprover.NullableValue(model.SafetyApproverDate); // set
    model.SafetyApproverDate = dtpSafetyApprover.NullableValue(); // get
    

提交回复
热议问题