views:

1505

answers:

3

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.

A: 

This should work:

private void Form1_Load(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.ValidatingType = typeof(System.DateTime);
    maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler
       (maskedTextBox1_TypeValidationCompleted);
}



private void TypeValidationCompletedHandler(object sender, TypeValidationEventArgs e )
{
    e.Cancel = !e.IsValidInput &&
        this.maskedTextBox1.MaskedTextProvider.AssignedEditPositionCount == 0;

}
Robert Harvey
That seems to have made it worse. Now it won't validate even if there was a null already in the textbox. Before it would work fine if it started out as null, it only doesn't work when there is a date that gets blanked out.
Aaron Smith
+3  A: 

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;
}
Aaron Smith
A: 

Experimenting with this i finally found an easier solution to this.

STEP 1:

Search the line that is binding your maskedtextbox (mine's called "mTFecha") in your Form.Designer.cs. i.e:

 // mTFecha
 // 
 this.mTFecha.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaAnimalesOfertadosBindingSource, "F_peso", true);

STEP 2:

Apply a minor hack:

this.mTFecha.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaAnimalesOfertadosBindingSource, "F_peso", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, "  /  /"));

You're Done!

sh4