Problem with MaskedTextBox for varying Currency Amounts

blackduck603

Member
Joined
Sep 17, 2008
Messages
21
Location
NH
Programming Experience
3-5
I am working on a VB application in Visual Studio 2005. I have a number of fields where the user needs to enter currency amounts. I am using a MaskedTextBox with the following currency mask.
msktxtAssessedVal.Mask = "$ #######.99"

The problem that I am having is that when the users type in the value, the cursor always starts at the leftmost position and appears to force that many digits. The typical data values can vary anywhere between 9,999,999.99 and 20,000.00. If the users do NOT have a value that has 7 digits left of the decimal point, they need to move the cursor to the correct position before they start typin in the value. These users are used to quickly typing in their data, then tabbing to the next field so the current behavior is not acceptable.

Does anyone know if there is a way for the maskedtextbox or any text control to detect where the user types the decimal and format the data accordningly?

I appreciate any suggestions.
 
The NumericUpDown control is better suited for this.
 
RE: NumericUpdown control

I actually found a promising VB Custom TextBox Control Class example that should address my issue. It is a CurrencyTextBox posted by Scott Lysle in March 2007. This example (at the link below) includes VB Project & Source files. I built it and ran some quick tests and it handles typed data entry very well - allowing the user to type in the decimal point at any position in the textbox instead of forcing it into a predefined position like with a MaskedTextBox.

Custom VB CurrencyTextBox Control - project & code


If it doesn't work out then I will check out the numeric up down control.

Thanks for taking the time to post.
- Bill
 
Here's what I figured out...

Set the Mask to "$###,###.99"

Put this in the MaskedTextBox KeyPress event...

VB.NET:
If e.KeyChar = "." Then
   With Me.MaskedTextBox1.Text.Replace(" ", "").Replace("$", "").Replace(",", "").Split(".")(0)
      Me.MaskedTextBox1.Text = Space(6 - .ToString.Length) & .ToString
   End With
End If

Note the 6 in the above code is the number of digits before the decimal. So if you change the mask, change this number accordingly.

The text property of MaskedTextBox1 will contain the literals so use this to get decimal value...

VB.NET:
   CType(Me.MaskedTextBox1.Text.Replace("$", "").Replace(",", "").ToString, Decimal)

Hope this helps,
Rick
 
Last edited:
Back
Top