Search code examples
c#winformsdatetimemaskedtextbox

c# Datetime bound textbox removes starting 0s


In c# Winforms, I have a textbox which is databound to a DateTime column in my database. When I type in something like the following into the textbox

05/12/1977

Once the textbox loses focus, the first 0 is removed so that it says

5/12/1977.

The reason this is a problem is because I actually want to use masked textbox so the /'s are already in the textbox for the user. But once the 0 is removed, the date gets messed up like so

51/21/977_

The date still saves correctly but this causes some of my form validation to not react properly since it views the masked textbox as not being completed. Anyone know of a way to prevent that first 0 from being removed?

Thanks!


Solution

  • This is just a problem with culture info. Since my textbox was databinded to a DateTime variable, all I had to do was change the method in which DateTime's are displayed as strings. The following code in my constructor of my GUI form fixed the problem

    var culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
    culture.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = culture;