Solved

VB 2010 - Date Displays Incorrectly in MaskedTextBox

Posted on 2010-11-23
27
2,183 Views
Last Modified: 2012-05-10
I am having difficulty displaying a datetime variable "DateCustom" to the user (in the correct format) via a masked textbox. I found a few articles that helped me further understand the problem (see below) but I am still unable to make this work.

This article helped me understand how dates are saved and why they display the way they do:
http://www.vbforums.com/archive/index.php/t-489286.html

Note: Changing the regional settings did fix the displaying of the date to the user but I am searching for a solution that will not require changing any settings at the computer level.

I also found these articles on the subject but perhaps my programming knowledge is insufficient to apply the code correctly:
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_25028943.html
http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_25659990.html

I have been going at this all day and I'm starting to lose my mind. Any input is greatly appreciated.
0
Comment
Question by:geteke
  • 12
  • 7
  • 7
  • +1
27 Comments
 
LVL 17

Expert Comment

by:Zhaolai
ID: 34201139
Try using DateTimePicker, see attached screenshot:
ScreenShot.png
0
 

Author Comment

by:geteke
ID: 34202141
I looked at that possibility but it doesn't fit our target design specs. I am trying to make the program easy/fast to tab through and enter the information necessary. If we are otherwise unable to accomplish this task then we will be forced to use this as a last resort.

Any other ideas?
0
 
LVL 17

Expert Comment

by:Zhaolai
ID: 34202823
What do you mean by "easy/fast to tab through"? The datetimepicker only take one tab.
0
 
LVL 21

Expert Comment

by:Alpesh Patel
ID: 34205253
You can set format for MaskEditor.
0
 

Author Comment

by:geteke
ID: 34205631
I set the MaskTextBox format to 00/00/0000 and it allows the entry of a date in that format without a problem. The problem arises after the user clicks save which performs an UpdateAll(). The MaskedTextBox now displays 05/05/2005 as 55/20/05__. I have discovered why this happens and its because of the user's regional settings.

My question is: Is there a way to override the user's regional settings in the program? If so, how do you do it? Or, preferably, Is there a way to universally set (through the entire project) that MaskedTextBox to *display* the date in the MM/dd/yyyy format.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34205679
You can change the culture used by application

http://visualbasic.about.com/od/usingvbnet/a/globvbnet1_2.htm
0
 
LVL 17

Expert Comment

by:Zhaolai
ID: 34206005
Try setting the MaskedTextBox format to ##/##/####.
0
 

Author Comment

by:geteke
ID: 34222368
I will try both ideas on Monday. Thanks!
0
 

Author Comment

by:geteke
ID: 34231707
Zhaolai: Setting the MaskedTextBox format to ##/##/#### did not work.

CodeCruiser: That link shows how to change the regional settings from one culture to another but really what I need is to change the en-US shortdate format from the default of M/d/yyyy to MM/dd/yyyy.

Ideally there is a line of code that I could insert at the top of my MainForm.vb that will allow me to do so globally for the entire instance of the program. This is what I am trying to find.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34231823
0
 

Author Comment

by:geteke
ID: 34232043
I have read about and researched (google) this matter extensively. Using the method you mentioned alters the Regional Settings on the PC. My aim is to not alter the PC's regional settings. By default the en-US shortdate format is M/d/yyyy and I want the program to simply ignore this format and display the date in a MM/dd/yyyy format.

So far I have been unsuccessful in finding a line (or lines) of code that I could insert at the top of my MainForm.vb that will allow me to simply output the shortdate in the MM/dd/yyyy format for the entire instance of the program. Does this option even exist?
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34232888
There is no magic in programming mate. You would have to handle the date as string if you want a format different than the system format. By the way, this link does not want you to change SYSTEM culture. It changes current THREAD's culture

http://#34205679
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34232896
That was ID of the comment above
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 17

Expert Comment

by:Zhaolai
ID: 34233078
As @CodeCruiser said, there is no such option in .NET to format the date for the entire application. You have to format it wherever you have to. It's a manual process, but not that bad at all.
First set the MaskedTextBox format to ##/##/####. Then try this:
If IsDate(MaskedTextBox1.Text) Then

            Dim strDate As String = CDate(MaskedTextBox1.Text).ToString("MM/dd/yyyy")

            MessageBox.Show(strDate)

        Else

            MessageBox.Show("Invalid date! Please try again.")

            MaskedTextBox1.Focus()

        End If

Open in new window

0
 

Author Comment

by:geteke
ID: 34233885
I tried it and that doesnt work either.

The program has a date variable that the user can change. Entering the values in this field are no problem. The problem arises when the date field is set to lets say 05/05/2010 or 01/09/2009. Once the user clicks save, the output on the MaskedTextBox shows as 55/20/10__ or 19/20/09__, respectively. The DB table shows the correct value but the MaskedTextBox *displays* the date according to the individual PC's regional settings (M/d/yyyy default for en-US). I simply need the MaskedTextBox to display the date in the MM/dd/yyyy format.

Below is some of the code that I have tried as well as our save function so that you can understand what is going on behind the scenes. Any help is greatly appreciated.

Private Sub DateFix()

        'Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US", False)

        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US", True)

        'Dim date1 As String = DateCustomMaskedTextBox.Text

        'DateCustomMaskedTextBox.Text = Format("MM/dd/yyyy")

        'DateCustomMaskedTextBox.Text = date1

        'DateCustomMaskedTextBox.Text = Format(Me.BFSDataSet.Customer(0)("DateCustom"), "MM/dd/yyyy")

    End Sub



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Call DateFix()

        'TODO: This line of code loads data into the 'OfficeLookupDataSet.OfficesTable' table. You can move, or remove it, as needed.

        Me.OfficesTableTableAdapter.Fill(Me.OfficeLookupDataSet.OfficesTable)



        saved = True

        'S = Format$(DateCustomMaskedTextBox.Text, "MM/dd/yyyy")

        RefundTextBox.Text = "0.00"

        EICTextBox.Text = "0.00"

        OChargeTextBox.Text = "0.00"

        BChargeTextBox.Text = "0.00"

        Call TextboxGrayOutOn()

    End Sub



Private Sub SaveData() As Double

        Call BlankFix()

        Call NoDataFix()

        DateTextBox.Text = DateAndTime.Now

        Me.Validate()

        Me.CustomerBindingSource.EndEdit()

        Me.TableAdapterManager.UpdateAll(Me.BFSDataSet)

        saved = True

    End Function

Open in new window

0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34233913
So the problem is only when displaying? Show us the code you use to set the maskedtextbox's value.
0
 

Author Comment

by:geteke
ID: 34233915
Forgive me, the SaveData() Sub used to be a function. It now reads:

Private Sub SaveData()
        Call BlankFix()
        Call NoDataFix()
        DateTextBox.Text = DateAndTime.Now
        Me.Validate()
        Me.CustomerBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.BFSDataSet)
        saved = True
    End Sub
 
0
 
LVL 17

Expert Comment

by:Zhaolai
ID: 34234114
Try this:
DateTextBox.Text = DateAndTime.Now.ToString("MM/dd/yyyy")
0
 

Author Comment

by:geteke
ID: 34234435
This is all I have that references the DateCustomMaskedTextBox. I am using a direct connection from the MaskedTextBox to the SQL table value.
Private Sub DateCustomMaskedTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)

        Dim allowedChars As String = "0123456789/"



        If allowedChars.IndexOf(e.KeyChar) = -1 Then

            ' Invalid Character

            e.Handled = True

        End If



        If e.KeyChar = Chr(8) Then

            ' allow backspaces

            e.Handled = False

        End If

    End Sub

Open in new window

0
 
LVL 17

Expert Comment

by:Zhaolai
ID: 34234476
Set your DateCustomMaskedTextBox's Mask like this:
ScreenShot.png
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34237076
This was said yesterday

Zhaolai: Setting the MaskedTextBox format to ##/##/#### did not work.
0
 

Author Comment

by:geteke
ID: 34259805
I found this code in the designer

'DateCustomMaskedTextBox
        '
        Me.DateCustomMaskedTextBox.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.CustomerBindingSource, "DateCustom", True))
        Me.DateCustomMaskedTextBox.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.DateCustomMaskedTextBox.Location = New System.Drawing.Point(409, 18)
        Me.DateCustomMaskedTextBox.Mask = "00/00/0000"
        Me.DateCustomMaskedTextBox.Name = "DateCustomMaskedTextBox"
        Me.DateCustomMaskedTextBox.ResetOnPrompt = False
        Me.DateCustomMaskedTextBox.Size = New System.Drawing.Size(100, 26)
        Me.DateCustomMaskedTextBox.TabIndex = 58
        Me.DateCustomMaskedTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center

I'm going to see if there is a line of code that I could input here that will allow me to set the output to the MM/dd/yyyy format.
0
 
LVL 17

Expert Comment

by:Zhaolai
ID: 34259833
Change the following line
Me.DateCustomMaskedTextBox.Mask = "00/00/0000"
to
Me.DateCustomMaskedTextBox.Mask = "##/##/####"
0
 

Accepted Solution

by:
geteke earned 0 total points
ID: 34259879
Zhaolai: I have done this repeatedly with no success.

After days of searching I found the answer.

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/7936b0c8-5901-446b-b464-70f80ca87482/

Finally!!

Thanks for all of your input guys I really appreciate the help.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34260850
That question is not solved. What was the solution for you?
0
 

Author Comment

by:geteke
ID: 34267931
This is what did it for me:

-----------------------------------------

Problem: If I bind a DateTime field to a masked text box with the default short date mask, the value fails to recognize a leading 0 and shifts all other digits one place to the left.

Solution: Select the MaskedTextBox.  Expand Databindings in Properties.  Click on the ellipses for “(Advanced)”

A dialog box appears where you can set a custom format.  Choose custom and select MM/dd/yyyy as the custom format.

I posted this because I looked everywhere trying to find an answer without success.  The Ladybug site (Bug ID FDBK21883) does not give an adequate answer.

Hope it helps someone.

Bryan

-----------------------------------------

I tried it and it worked like a charm.
0
 

Author Closing Comment

by:geteke
ID: 34289883
This solution meets all of my criteria perfectly.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now