Bind a DateTime variable to a MaskedTextBox

I have a hidden text field attached to a nullabe time date, but when the date fades, the check in the hidden text field will not complete. Is there any way to force this behavior? I want the empty text field to be null DateTime.

When the text field is already null, a check is performed. It only breaks when there is a date already linked, and I'm trying to exclude it.

+6
c # datetime nullable data-binding maskedtextbox
source share
5 answers

I realized that this is not related to validation. This was when the date was parsed back to datetime.

It may not be the most elegant way to do this, but it really works. If anyone knows a better way, 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; } 
+4
source share

I use this with maskedtextbox for datetime type

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

if necessary, null the date value, use the null-datetime type in the class declaration:

 private DateTime? _DateBrth; public DateTime? DateBrth { get { return _DateBrth; } set { _DateBrth = value; } } 
+1
source share

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; } 
0
source share

By experimenting with this, I finally found an easier solution to this.

STEP 1:

Find the line that binds your maskedtextbox (mine, 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 minor hack:

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

You are ready!

0
source share

You can simply specify the date format as shown below:

 maskTextBox1.DataBindings.Add("Text", bs, "SummitDate1", true, DataSourceUpdateMode.OnPropertyChanged, null, "dd/MM/yyyy"); 
0
source share

All Articles