Wednesday, July 3, 2013

Properly Formatting Dates When DataBinding to a MaskedTextBox Control

Sometimes using MaskedTextBox control in a Windows Form does not display correctly the date when you bind it with a DateTime data type. It removes the leading ZEROES of the date when you run the program. Like this example below:


The solution is before databinding the MaskedTextBox control to the DataSet at runtime, you should apply the necessary format string you want your date to be displayed. Check out the code below for the solution (txtDateHired as the name of the MaskedTextBox Control):

Binding dateHired = new Binding("Text", ds, "Employees.DateHired");
dateHired.FormattingEnabled = true;
dateHired.FormatString = "MM/dd/yyyy";
txtDateHired.DataBindings.Add(dateHired);

Using this code, the dates will display properly on the form when using a MaskedTextBox control as part of your User Interface.