Solved

i cannot get a textbox to have a mask, i need to enter a currency value only into textbox

Posted on 2004-04-22
5
1,336 Views
Last Modified: 2012-05-04
what i need to do is when a user enters a value, only let numerical values be entered into the textbox
ATTEMPT1
i have tried a good few examples, on this site, there is some source code but i cannot download the project for some reason
http://www.codeproject.com/vb/net/cpflexmaskeditbox.asp

ATTEMPT2
another question in experts exchange told the user to register "Microsoft Masked Edit Control, version 6.0""
but now what?
i dont see an extra property in the textboxes now

ATTEMPT3
and then bobjohnson187@??????.com posted this code in a post , and i made a class out of it but i dont know what to do next
'---------------------------------------------------
Public Class TextBoxNumeric
    Inherits System.Windows.Forms.TextBox

#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        'This call is required by the Windows Form Designer.
        InitializeComponent()
        'Add any initialization after the InitializeComponent() call
    End Sub
    'UserControl1 overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        components = New System.ComponentModel.Container
    End Sub
#End Region

    Dim m_IntegerOnly As Boolean
    Dim m_PositiveOnly As Boolean
    '<Description("If TRUE, only integers can be entered."), _
    'Browsable(True), _
    'Category("Validation"), _
    'DefaultValue(False)> _
    Property IntegerOnly() As Boolean
        Get
            Return m_IntegerOnly
        End Get
        Set(ByVal Value As Boolean)
            m_IntegerOnly = Value
        End Set
    End Property
    '<Description("If TRUE, only positive numbers can be entered."), _
    'Browsable(True), _
    'Category("Validation"), _
    'DefaultValue(False)> _
    Property PositiveOnly() As Boolean
        Get
            Return m_PositiveOnly
        End Get
        Set(ByVal Value As Boolean)
            m_PositiveOnly = Value
        End Set
    End Property
    Private Sub NumericTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        Dim KeyAscii As Integer
        KeyAscii = Asc(e.KeyChar) ' NOTE: used as a flag when = 0 to mark bad values
        Select Case KeyAscii
            Case 48 To 57, 8, 13 ' Digits 0 - 9, Backspace, CR.
                ' These are OK, so accept them.
            Case 45 ' Minus sign.
                If PositiveOnly Then
                    KeyAscii = 0
                Else
                    ' Number can have only one minus sign, so if
                    ' we already have one, throw this one away.
                    If InStr(Me.Text, "-") <> 0 Then
                        KeyAscii = 0
                    End If
                    ' If the insertion point is not sitting at zero
                    ' (i.e., the beginning of the field), throw away
                    ' the minus sign because it's not valid anywhere
                    ' but the first position
                    If Me.SelectionStart <> 0 Then
                        KeyAscii = 0
                    End If
                End If
            Case 46 ' Period (decimal point).
                If IntegerOnly Then
                    KeyAscii = 0
                Else
                    ' If we already have one period, throw it away
                    If InStr(Me.Text, ".") <> 0 Then
                        KeyAscii = 0
                    End If
                End If
            Case Else ' Provide no handling for other keys.
                KeyAscii = 0
        End Select
        ' If we want to throw the keystroke away, then set the event
        ' as already handled. Otherwise, let the keystroke be
        ' handled normally.
        If KeyAscii = 0 Then
            e.Handled = True
        Else
            e.Handled = False
        End If
    End Sub
'---------------------------------------------------
ATTEMPT4
http://www.c-sharpcorner.com/Download.asp?file=/Code/2004/Jan/MaskedTextBoxJP.zip
but this is in C# and im doing vb.net, maybe there is still a way to use it if someone can help me


personally i would like to get option 2 or 3 working

thank you
0
Comment
Question by:jxharding
  • 2
  • 2
5 Comments
 
LVL 28

Expert Comment

by:iboutchkine
Comment Utility
Here are several examples for you

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
        If Char.IsDigit(e.KeyChar) Then
            MsgBox("Digit entered")
        End If
        'disable non-digits
        e.Handled = Not Char.IsDigit(e.KeyChar)
    End Sub

Be aware
that there are a couple potential problems with these solutions.

   - can't backspace to edit an entry
   - can't paste valid data with keyboard
   - can paste invalid data with mouse
   - can't copy data with keyboard
some thoughts
The text in the textbox should by validated in the validating event and
not when the user types the text. Preventing the user from entering
characters can be annoying, for example when entering a negative number
you should not prevent the user from entering more than one "-"
character. The user is responsible for the proper format, when the focus
is set to an other control, the content gets validated. You can use an
ErrorProvider control to make the user aware of malformed or invalid
input.

'---another one ---
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "
#End Region
    Protected Overrides Function ProcessDialogKey(ByVal keydata As System.Windows.Forms.Keys) As Boolean
        If Me.TextBox1.Focused Then
            Select Case keydata
                Case Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9, Keys.Back  'accept digits only and Backspace
                    Return False
                Case Else
                    Return True
            End Select
        Else
            Return MyBase.ProcessDialogKey(keydata)
        End If
    End Function
End Class
'----another----------
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    e.Handled = NumbersOnly(e.KeyChar, TextBox1)
End Sub
   
Private Function NumbersOnly(ByVal pstrChar As Char, ByVal oTextBox As TextBox) As Boolean
    'validate the entry for a textbox limiting it to only numeric values and the decimal point
    If (Convert.ToString(pstrChar) = "." And InStr(oTextBox.Text, ".")) Then Return True 'accept only one instance of the decimal point
    If Convert.ToString(pstrChar) <> "." And pstrChar <> vbBack Then
    Return IIf(IsNumeric(pstrChar), False, True) 'check if numeric is returned
    End If
    Return False 'for backspace
End Function
0
 
LVL 35

Expert Comment

by:YZlat
Comment Utility
     <script language="JavaScript">
            <!--
            //****************************************************************************
            //purpose            : Masks a numeric value by placing a dollar sign ($) and
            //                                 comma/commas in appropriate places.
            //example            :  onBlur="this.value=formatCurrency(this.value);"
            //input parameters   : numeric value
            //returns            : currency field with dollar sign and commas in appropriate places
            //function calls made: none
            //****************************************************************************
            
            function formatCurrency(num) {
                  num = num.toString().replace(/\$|\,/g,'');
                  if(isNaN(num))
                        num = "0";
                  sign = (num == (num = Math.abs(num)));
                  num = Math.floor(num*100+0.50000000001);
                  cents = num%100;
                  num = Math.floor(num/100).toString();
                  if(cents<10)
                        cents = "0" + cents;
                  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
                        num = num.substring(0,num.length-(4*i+3))+','+
                        num.substring(num.length-(4*i+3));
                  return (((sign)?'':'-') + '$' + num + '.' + cents);
            }
            
//-->
</script>

In your Page_Load put the following code:

Text1.Attributes.Add("onblur", "this.value=formatCurrency(this.value);"
0
 

Author Comment

by:jxharding
Comment Utility
i just got ATTEMPT1 working but i dont like the component so much
then  i read the first post from iboutchkine, and i saw all the warnings that was given, and i thought
damn.
then i went to to check how the world renowned accounting program we bought handles this situation with the validation  , and guess what:
it also has all the potential problems iboutchkine mentioned!
so i think if its good enough for them, its good enough for me.
im just gonna try them all out.
thanks!
0
 

Author Comment

by:jxharding
Comment Utility
ibouthckine, id like to use this sub:

 Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles
TextBox2.KeyPress
        If Char.IsDigit(e.KeyChar) Then
            MsgBox("Digit entered")
        End If
        'disable non-digits
        e.Handled = Not Char.IsDigit(e.KeyChar)
    End Sub

is there any way to modify : "        e.Handled = Not Char.IsDigit(e.KeyChar)"
so i can use "." or "," as well to have decimal?
the value i want to enter is monetary

0
 
LVL 28

Accepted Solution

by:
iboutchkine earned 500 total points
Comment Utility
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If Char.IsDigit(e.KeyChar) Or e.KeyChar = "."c Or e.KeyChar = ","c Then ' you can add more char if you want
            MsgBox("Digit entered")
        Else
            e.Handled = True
        End If
 End Sub
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
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…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

743 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

13 Experts available now in Live!

Get 1:1 Help Now