Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind nullable DateTime to MaskedTextBox

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 behaviour? I want a blanked out text box to equal a null DateTime.

When the textbox is already null, the validation works. It only breaks when there is a date already bound and I try to blank it out.

like image 765
Aaron Smith Avatar asked Jun 11 '09 16:06

Aaron Smith


2 Answers

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;
}
like image 158
Aaron Smith Avatar answered Sep 29 '22 05:09

Aaron Smith


I use this with maskedtextbox for datetime type

this.txtDateBrth.DataBindings.Add("Text", bsAgent, "DateBrth", true, DataSourceUpdateMode.OnPropertyChanged, null, "dd/MM/yyyy");

if need null date value, use nullable datetime type in class declaration :

private DateTime? _DateBrth;
        public DateTime? DateBrth
        {
            get { return _DateBrth; }
            set { _DateBrth = value; }
        }
like image 39
AZOUZ24 Avatar answered Sep 29 '22 05:09

AZOUZ24