Bind nullable DateTime to MaskedTextBox

后端 未结 5 1633
遇见更好的自我
遇见更好的自我 2021-01-18 05:59

I have a masked text box bound to a nullabe datetime, but when the date is blanked out, the validation on the masked text box won\'t complete. Is there a way to force this

5条回答
  •  春和景丽
    2021-01-18 06:13

    I figured out it didn't have to do with the validation. It was when the date was being parsed back to the datetime.

    This may not be the most elegant way to do this, but it does work. If anyone knows a better way, please let me know.

    I have this code now.

    public static void FormatDate(MaskedTextBox c) {
        c.DataBindings[0].Format += new ConvertEventHandler(Date_Format);
        c.DataBindings[0].Parse += new ConvertEventHandler(Date_Parse);
    }
    
    private static void Date_Format(object sender, ConvertEventArgs e) {
        if (e.Value == null)
            e.Value = "";
        else
            e.Value = ((DateTime)e.Value).ToString("MM/dd/yyyy");
    }
    
    static void Date_Parse(object sender, ConvertEventArgs e) {
        if (e.Value.ToString() == "  /  /")
            e.Value = null;
    }
    

提交回复
热议问题